<?php

namespace app\api\controller;

use app\api\model\ConfigPrice;
use app\api\model\Juhe;
use app\api\model\OrderCommon;
use app\api\model\Topup;
use OSS\Core\OssException;
use OSS\OssClient;
use think\Db;
use app\api\model\Cluster;
use think\Request;
use think\Log;
use app\api\model\ConfigSystem as Config;
use app\api\model\User;
use app\api\model\Dymanic;
use app\api\model\Timing as TimingModel;
use app\api\model\UserBalance;
use app\api\model\UserData;
use app\api\model\UserTeam;
use app\api\model\UserActiveval;
use app\api\model\YaoqingRecords;
use app\api\model\Privatechat;
use app\api\model\UserPunish;
use app\api\model\VolleyDesc as Balance;
use app\api\model\PrivatechatDeleTask;
use app\api\model\UserPornoStatis;
use app\service\UserIntimate;
use GatewayClient\Gateway;
use Mrgoon\AliSms\AliSms;
use Qcloud\Cos\Client;
use app\service\UserRepeat;
use think\Cache;
use app\service\BaiduApi;

class Timing extends Common
{
    // 返还聊天金额 (1分钟)
    private function returnMoney()
    {
        $data = Db::name('privatechat')->where([
            'score' => ['gt', 0],
            'finish' => 0,
            'addtime' => ['elt', date('Y-m-d H:i:s', strtotime('-72 hour'))]
        ])->select();

        if ($data) {
            $tips = [];

            $ids = array_column((array)$data, 'touserid');

            $users = Db::name('user')->where(['id' => ['in', $ids]])->column('id, name, phone');

            $uids = array_column((array)$data, 'userid');
            $users_balance = Db::name('user')->where(['id' => ['in', $uids]])->column('id, volley');

            $giftIds = [];
            foreach ($data as $item) {
                if ($item['type'] == 8) {
                    $datas = json_decode($item['data'], true);
                    $giftIds[] = $datas['id'];
                }
            }

            $gifts = [];
            if ($giftIds) {
                $gifts = Db::name('user')->where(['id' => ['in', $giftIds]])->column('id, name');
            }

            $ids = array_column((array)$data, 'id');
            Db::name('privatechat')->where(['id' => ['in', $ids]])->setField('finish', 1);
            $desc = [];
            $tongji_unreply_list_records = [];
            $Today = date('Y-m-d');
            foreach ($data as $item) {
                if ($item['money'] > 0 && isset($users_balance[$item['userid']])) {
                    Db::name('user')->where(['id' => $item['userid']])->setInc('volley', $item['money']);

                    $users_balance[$item['userid']] += $item['money'];

                    if (isset($users[$item['touserid']])) {
                        $name = $users[$item['touserid']]['name'];
                        $id = $users[$item['touserid']]['id'];
                    } else {
                        $name = '账号已注销';
                        $id = '未知';
                    }

                    if ($item['type'] == 8) {
                        $datas = json_decode($item['data'], true);

                        if (isset($gifts[$datas['id']])) {
                            $giftName = $gifts[$datas['id']];
                        } else {
                            $giftName = '未知';
                        }

                        $msg = $name . '(' . $id . ')未领取礼物【' . $giftName . '】，过期返还金币';
                    } else {
                        $msg = $name . '(' . $id . ')未回复消息，过期返还金币';
                    }

                    $desc[] = [
                        'user_id' => $item['userid'],
                        'content' => $msg,
                        'price' => $item['money'],
                        'types' => 1,
                        'balance' => $users_balance[$item['userid']],
                        'time' => time()
                    ];
                    $tongji_unreply_list_records[] = [
                        'userid' => $item['userid'],
                        'touserid' => $item['touserid'],
                        'chat_id' => $item['id'],
                        'chat_single' => $item['single'],
                        'chat_status' => $item['status'],
                        'chat_isread' => $item['isRead'],
                        'chat_content' => $item['content'],
                        'chat_addtime' => $item['addtime'],
                        'date' => $Today
                    ];

                    if (array_key_exists($item['userid'] . ',' . $item['touserid'], $tips)) {
                        $tips[$item['userid'] . ',' . $item['touserid']] += $item['money'];
                    } else {
                        $tips[$item['userid'] . ',' . $item['touserid']] = $item['money'];
                    }
                }
            }

            Db::name('volley_desc')->insertAll($desc);
            Db::name('tongji_unreply_list_records')->insertAll($tongji_unreply_list_records);


            if ($tips) {
                $tipsMeta = [];
                foreach ($tips as $key => $item) {
                    $both = explode(',', $key);

                    if (isset($both['userid']) && isset($both['touserid'])) {
                        $tipsMeta[] = [
                            "type" => -1,
                            "userid" => $both['touserid'],
                            "touserid" => $both['userid'],
                            "content" => '对方未及时回复消息，' . $item . '金币已经退还到您的账户',
                            'single' => 1,
                            'isRead' => 1,
                            'sound_tip' => 1,
                            'finish' => 1
                        ];
    
                        $tipsMeta[] = [
                            "type" => -1,
                            "userid" => $both['userid'],
                            "touserid" => $both['touserid'],
                            "content" => '您没有及时回复对方的消息，' . $item . '金币已被退回',
                            'single' => 1,
                            'isRead' => 1,
                            'sound_tip' => 1,
                            'finish' => 1
                        ];
                    }
                }
                Db::name('privatechat')->insertAll($tipsMeta);
            }
        }
    }

    // 群排行 (30分钟)
    private function clusterRanking()
    {
        $data = Db::name('cluster')->where(['types' => 1, 'status' => 1])->order('active desc')->select();

        $contain = [];
        foreach ($data as $key => $item) {
            $contain[] = ['id' => $item['id'], 'ranking' => $key + 1];
        }

        if ($contain) {
            (new Cluster)->saveAll($contain);
        }

        Db::name('cluster')->where(['types' => 1, 'status' => ['neq', 1]])->setField('ranking', 0);

    }

    // 留存率记录 (00:05)
    private function tongjiUser()
    {
        $date = date('Y-m-d', strtotime('-1 day'));

        $data = Db::name('tongji_user')->where(['date' => $date])->find();

        if (!$data) {
            $count = Db::name('user')->where(['reg'=>1,'remote'=>0])->whereTime('register_datetime', 'yesterday')->count();

            Db::name('tongji_user')->insert(['new_user' => $count, 'date' => $date, 'create_time' => time()]);
        }

        $day = 30;

        $data = Db::name('tongji_user')->master()->whereTime('create_time', '-'.$day.' days')->select();
        $users = Db::name('user')
                    ->where(['reg'=>1,'remote'=>0])
                    ->whereTime('register_datetime', '-'.($day + 2).' days')
                    ->field('id,UNIX_TIMESTAMP(register_datetime) register_datetime,UNIX_TIMESTAMP(last_login_datetime) last_login_datetime')
                    ->select();

        foreach ($data as $key => $item) {

            if ($item['new_user']) {
                $start = strtotime($item['date']);
                $end = $start + 86399;

                $update = [];

                $contain = ['next_day' => 1, 'three_day' => 2, 'four_day' => 3, 'five_day' => 4, 'six_day' => 5, 'seven_day' => 6, 'fifteen_day' => 14, 'thirty_day' => 29];

                foreach ($contain as $m => $n) {
                    $$m = strtotime($item['date']) + 86400 * $n;

                    if ($$m < time()) {
                        $count = 0;
                        foreach ($users as $ukey => $uvalue) {
                            if ($uvalue['register_datetime'] >= $start && $uvalue['register_datetime'] <= $end && $uvalue['last_login_datetime'] > $$m) {
                                $count += 1;
                            }
                        }

                        $update[$m . '_keep'] = $count / $item['new_user'];
                    }
                }

                Db::name('tongji_user')->where(['id' => $item['id']])->update($update);
            }
        }
    }

    // 代理团队留存率记录 (00:10)
    private function tongjiProxy()
    {
        $date = date('Y-m-d', strtotime('-1 day'));

        $data = Db::name('tongji_proxy')->where(['date' => $date])->find();

        if (!$data) {
            $users = Db::name('user')->whereTime('register_datetime', 'yesterday')->select();

            $time = time();
            $contain = [];
            foreach ($users as $key => $item) {
                if ($item['yqr']) {
                    $parent = Db::name('user')->where(['yqm' => $item['yqr']])->value('id');

                    if ($parent) {
                        if (isset($contain[$parent])) {
                            $contain[$parent]['new_user']++;
                        } else {
                            $contain[$parent] = ['user_id' => $parent, 'new_user' => 1, 'date' => $date, 'create_time' => $time];
                        }
                    }
                }
            }

            if ($contain) {
                Db::name('tongji_proxy')->insertAll($contain);
            }
        }


        // 延迟10秒，避免主从数据还未同步玩就执行下一个删除操作出现数据不一致导致主从同步断开
        sleep(10);

        $data = Db::name('tongji_proxy')->whereTime('create_time', '-30 days')->select();

        foreach ($data as $key => $item) {

            if ($item['new_user']) {
                $start = date('Y-m-d H:i:s', strtotime($item['date']));
                $end = date('Y-m-d H:i:s', (strtotime($item['date']) + 86399));

                $update = [];

                $contain = ['next_day' => 1, 'three_day' => 2, 'four_day' => 3, 'five_day' => 4, 'six_day' => 5, 'seven_day' => 6, 'fifteen_day' => 14, 'thirty_day' => 29];

                foreach ($contain as $m => $n) {
                    $$m = strtotime($item['date']) + 86400 * $n;

                    if ($$m < time()) {
                        $yqm = Db::name('user')->where(['id' => $item['user_id']])->value('yqm');

                        if ($yqm) {
                            $count = Db::name('user')->where(['yqr' => $yqm, 'register_datetime' => ['between', [$start, $end]], 'last_login_datetime' => ['gt', date('Y-m-d H:i:s', $$m)]])->count();

                            $update[$m . '_keep'] = $count / $item['new_user'];
                        }
                    }
                }

                Db::name('tongji_proxy')->where(['id' => $item['id']])->update($update);
            }
        }
    }

    // 清除打招呼记录(00:00)
    private function emptyGreet()
    {
        //$start = strtotime(date('Ymd')) - 86400 * 3;
        //Db::name('greet_records')->where(['create_time' => ['lt', $start]])->delete();
        try {
            Db::name('user')->where(['greet_count' => ['gt', 0]])->update(['greet_count' => 0, 'greet_time' => time(), 'greet_receive_count' => 0, 'greet_receive_time' => time()]);
        } catch (Exception $e) {
            
        }
    }

    // 处理VIP过期 (23:55)
    private function checkNoble()
    {
        $timenow = time();
        $uids = Db::name('user')->where(['noble_time' => ['elt', $timenow], 'noble_grade' => ['>', 0]])->column('id');
        Db::name('user')->where(['id' => ['in', $uids]])->setField('noble_grade', 0);

        $userNoble = Db::name('user_noble')->where(['expire' => ['gt', $timenow]])->order('grade asc')->column('user_id, grade');

        if ($userNoble) {
            $ids = array_keys($userNoble);

            $users = Db::name('user')->where(['id' => ['in', $ids], 'noble_time' => ['gt', $timenow]])->column('id, noble_grade');

            $contain = [];

            foreach ($userNoble as $key => $item) {
                if (isset($users[$key]) && $item < $users[$key]) {
                    $contain[] = ['id' => $key, 'noble_grade' => $item];
                }
            }

            if ($contain) {
                try {
                    (new User)->saveAll($contain);
                } catch (Exception $e) {
                    
                }
            }
        }
    }

    // 平台每日利润 (00:00)
    public function bill()
    {
        /*$expense = Db::name('platform_balance')->where(['types' => 1])->whereTime('create_time', 'd')->sum('money');
        $income = Db::name('platform_balance')->where(['types' => 2])->whereTime('create_time', 'd')->sum('money');

        $result = Db::name('platform_bill')->where(['date' => date('Y-m-d')])->find();

        if (!$result) {
            $profit = $income - $expense;

            Db::name('platform_bill')->insert(['income' => $income, 'expense' => $expense, 'profit' => $profit, 'date' => date('Y-m-d'), 'create_time' => time()]);
        }*/

        $yesterday_date = date('Y-m-d', strtotime('-1 day', strtotime(date('Y-m-d'))));

        $income = Db::name('topup')->where(['state' => 1])->whereTime('addtime', 'yesterday')->sum('price');
        $expense = Db::name('yaoqing_records t1')
            ->join('user t2', 't2.id = t1.uid')
            ->where([
                't1.type' => 1,
                't1.data' => 0,
               // 't1.content' => ['like', '%收益'],
                't2.sex' => '女',
                't2.is_identity_authentication' => 2
            ])->whereTime('time', 'yesterday')->sum('money');

        $total = Db::name('user')->field('sum(volley) volley_total, sum(score) score_total')->where(['id' => ['gt', 0]])->find();

        $withdraw = Db::name('withdraw')->where(['state' => ['in', [0, 1]]])->whereTime('create_time', 'yesterday')->sum('money');
        $present_coin = Db::name('volley_desc')->where(['content' => ['in', ['充值赠送', '充值VIP赠送']]])->whereTime('time', 'yesterday')->sum('price');

        $result = Db::name('platform_bill')->where(['date' => $yesterday_date])->find();

        if (!$result) {
            Db::name('platform_bill')->insert([
                'income' => $income,
                'expense' => $expense,
                'user_coin' => $total['volley_total'],
                'user_score' => $total['score_total'],
                'present_coin' => $present_coin,
                'withdraw' => $withdraw,
                'date' => $yesterday_date,
                'create_time' => time()
            ]);
        }
    }

    // 删除冗余数据 (00:05)
    private function emptyData()
    {
        // Db::name('privatechat')->where(['type' => ['in', ['-1', '-2']], 'addtime' => ['lt', date('Y-m-d H:i:s', strtotime('-1 day'))]])->delete();
        // Db::name('clusterchat')->where(['type' => ['in', ['-1', '-2']], 'addtime' => ['lt', date('Y-m-d H:i:s', strtotime('-5 day'))]])->delete();

        // Db::name('sys_message')->where(['create_time' => ['lt', date('Y-m-d H:i:s', strtotime('-1 day'))]])->delete();

        Db::name('proxy_visit_records')->where(['create_time' => ['lt', strtotime('-5 day')]])->delete();
        Db::name('records_mate')->where(['create_time' => ['lt', strtotime('-5 day')]])->delete();

        // $contents = Db::name('privatechat_zhaohu')->column('content');
    
        // $contents[] = '❤ ← 丘比特 → 发现你俩今天很有缘，为你们牵线成功~';
        // $contents[] = '❤ ← 丘比特 → 牵线成功，给对方发消息可领取红包奖励';

        // Db::name('privatechat')->where(['content' => ['in', $contents], 'addtime' => ['lt', date('Y-m-d H:i:s', strtotime('-2 day'))]])->delete();

        Db::name('privatechat')->where(['data' => '{"prefix":"丘比特"}', 'addtime' => ['lt', date('Y-m-d H:i:s', strtotime('-2 day'))]])->delete();

        // VIP聊天特权次数使用记录
        Db::name('grade_noble_use')->where(['id' => ['gt', 0]])->delete();

        /*$kefu = Db::name('config_system')->where(['title' => 'id'])->value('content');
        $kefu = intval($kefu);*/

        //Db::name('privatechat')->where(['content' => ['neq', '我在这儿呢'], 'addtime' => ['lt', date('Y-m-d H:i:s', strtotime('-3 day'))]])->delete();
    
        Db::name('topup')->where(['state' => 2])->delete();
        Db::name('order_common')->where(['status' => -1])->delete();
        Db::name('user_car')->where(['expire' => ['lt', time()]])->delete();
        

        $task = Db::name('task')->where(['types' => 2])->column('name');
        if ($task) {
            $today_start = strtotime(date('Y-m-d'));
            Db::name('user_task')->where(['task' => ['in', $task], 'create_time' => ['lt', $today_start]])->delete();
        }
    }

    public function clearwalletrecords()
    {
        // Db::name('volley_desc')->where(['time' => ['lt', strtotime('-2 day')]])->delete();
        // Db::name('yaoqing_records')->where(['time' => ['lt', strtotime('-2 day')]])->delete();
        Db::name('chat_warn')->where(['create_time' => ['lt', strtotime('-2 day')]])->delete();
    }

    // 删除冗余数据 (30分钟)
    private function emptyGreetRecords()
    {
        $ids1 = [];
        $ids2 = [];
        $user1 = [];
        $user2 = [];
        $data = Db::name('see_record')->order('addtime desc, id desc')->select();
    
        foreach ($data as $item) {
            if (!isset($user1[$item['user_id']]) || count($user1[$item['user_id']]) < 10) {
                $user1[$item['user_id']][] = $item['id'];
                $ids1[] = $item['id'];
            }
    
            if (!isset($user2[$item['the_user']]) || count($user2[$item['the_user']]) < 10) {
                $user2[$item['the_user']][] = $item['id'];
                $ids2[] = $item['id'];
            }
        }
    
        $ids = array_unique(array_merge($ids1, $ids2));
        Db::name('see_record')->where(['id' => ['not in', $ids]])->delete();
        
        $sql = "delete from greet_records where (user_id,to_user)
                in
                (select user_id,to_user from (select user_id,to_user from greet_records where id in (select id from greet_records group by user_id,to_user having count(*) > 1)  order by id) t) and id not in (select id from (select max(id) id from greet_records group by user_id,to_user having count(*) > 1) s)";
        Db::query($sql);
    }


    // 未读消息 新短信提醒 (5分钟)
    public function ChatSmsTip()
    {

        $cachekey = 'Timing:ChatSmsTipLastId';
        $lastid = cache($cachekey)?:0;

        $config = Db::name('config_system')->where(['category' => ['in', ['greet', 'kefu']]])->column('title, content');

        $kefu = (int)strip_tags($config['id']);

        $where = [
            'type' => ['in', ['0', '1', '2', '3', '8', '12', '13', '14', '15', '16']],
            'userid' => ['neq', $kefu],
            'touserid' => ['neq', $kefu],
            'content' => ['neq', '{"prefix":"丘比特"}'],
            'isRead' => 0,
            'sms_tip' => 0,
            'addtime' => ['between', [date('Y-m-d H:i:s', strtotime('-10 minute')), date('Y-m-d H:i:s', strtotime('-5 minute'))]]
        ];

        if ($lastid) {
            $where['id'] = ['>', $lastid];
        }

        $data = Db::name('privatechat')->where($where)->group('touserid')->limit(300)->select();

        // echo "<pre>";
        // var_dump($data);exit;

        if ($data) {
            $unsmstip_switchs = Db::name('config_personal')->where(['user_id'=>['in', array_column($data, 'touserid')]])->column('unsmstip_switch','user_id');
            $insertSendRecords = $ids = $uids = [];
            $time = time();
            foreach ($data as $key => $item) {
                $lastid = $item['id'];
                $ids[] = $item['id'];
                if (isset($unsmstip_switchs[$item['touserid']]) && $unsmstip_switchs[$item['touserid']]) {
                    continue;
                }
                $smsSendRecord = ['user_id'=>$item['userid'], 'another_id'=>$item['touserid']];
                $tmp = Db::name('chat_lists_smstip')->where($smsSendRecord)->cache(60)->find();
                $todaysend = Db::name('chat_lists_smstip')->where(['another_id'=>$item['touserid']])->whereTime('time','-168 hours')->cache(60)->find();
                if($tmp || $todaysend){
                    continue;
                }else{
                    $smsSendRecord['time'] = $time;
                    $insertSendRecords[] = $smsSendRecord;
                }
                if (!in_array($item['touserid'], $uids)) {
                    $uids[] = $item['touserid'];
                }
            }

            if ($uids) {
                $users = Db::name('user')->where(['id' => ['in', $uids], 'phone' => ['not in', [' ', 'null']], 'role' => 0, 'quality'=>['<>',1], 'is_banned'=>0])->field('id,is_online,sex,phone,last_login_datetime')->select();
                $userDatas = Db::name('user_data')->where(['user_id'=>['in',array_column($users,'id')]])->column('topup','user_id');
                // var_dump($users);exit;
                if (sizeof($users)) {
                    // $juhe = new Juhe();
                    $aliSms = new AliSms();
                    $config = [
                        'access_key' => getenv('ALICLOUD_ID'),
                        'access_secret' => getenv('ALICLOUD_SECRET'),
                        'sign_name' => '那蓝之恋app',
                    ];
                    foreach ($users as $value) {
                        if (isset($userDatas[$value['id']]) && $userDatas[$value['id']] > 10000) continue;
                        // 当前在线的不发送
                        if($value['is_online'] == 1 && strtotime($value['last_login_datetime']) + 3600 > $time){
                            if(sizeof($insertSendRecords) == 0){
                                break;
                            }
                            for ($i=sizeof($insertSendRecords) - 1; $i >= 0 ; $i--) {
                                if(isset($insertSendRecords[$i]) && $insertSendRecords[$i]['another_id'] == $value['id']){
                                    unset($insertSendRecords[$i]);
                                }
                            }
                            continue;
                        }
                        try {
                            $aliSms->sendSms($value['phone'], 'SMS_460970161', [], $config);
                            // $res = $juhe->send($value['phone']);
                            // var_dump($res);exit;
                        } catch (Exception $e) {
                            
                        }
                    }
                }
                
            }


            // var_dump($users);
            // exit;

            if (sizeof($ids)) {
                Db::name('privatechat')->where(['id' => ['in', $ids]])->setField('sms_tip', 1);
            }
            if (sizeof($insertSendRecords)) {
                Db::name('chat_lists_smstip')->insertAll($insertSendRecords);
            }

            cache($cachekey, $lastid, 86400);
        }
    }


    public function hours()
    {
        $this->checkOrder();
        // $this->clusterRanking();
        $this->returnMoney();
        $this->deleteChatLists();
        // $this->emptyGreetRecords();
        // $this->setOnlineAll();
        $this->rmSelectUser();
        // $this->yesterdayActivevalDec();
    }

    private function yesterdayActivevalDec()
    {
        $deconce = Config::where(['category'=>'useractiveval', 'title'=>'dec_once'])->value('content');
        if($deconce < 0){
            return false;
        }
        $UserActivevalupdateUsers = [];
        $updateUsers = [];
        $list = Db::name('user_activeval')->where('yesterday','>',0)->order('yesterday', 'desc')->select();
        $num = 0;
        foreach ($list as $key => $value) {
            try {
                $decval = $value['yesterday'] * $deconce / 100;
                if ($decval < 0.01) $decval = 0.01;
                if (!isset($UserActivevalupdateUsers[$num])) {
                    $UserActivevalupdateUsers[$num] = [];
                }
                if (sizeof($UserActivevalupdateUsers[$num]) > 500) ++$num;
                $UserActivevalupdateUsers[$num][] = [
                    'user_id'=>$value['user_id'],
                    'yesterday'=>Db::raw('yesterday-'.$decval)
                ];
                $updateUsers[$num][] = [
                    'id'=>$value['user_id'],
                    'activeval'=>Db::raw('activeval-'.$decval)
                ];
            } catch (\Exception $e) {
                
            }
        }
        if (sizeof($updateUsers)) {
            $UserActivevalModel = new UserActiveval;
            $userModel = new User;
            foreach ($updateUsers as $k => $v) {
                $UserActivevalModel->saveAll($UserActivevalupdateUsers[$k]);
                $userModel->saveAll($v);
                sleep(10);
            }
        }
    }
    private function userActivevalRefresh()
    {
        return fasle;
        try {
            $list = Db::name('user_activeval')->where('today','>',0)->select();
            foreach ($list as $key => $value) {
                $list[$key]['yesterday'] += $value['today'];
                $list[$key]['today'] = 0;
            }
            $UserActiveval = new UserActiveval;
            $UserActiveval->saveAll($list);
        } catch (\Exception $e) {
            Log::write('活跃度刷新失败 ' . $e->getMessage());
        }
    }

    public function days()
    {
        try {
            $this->userBalance();
        } catch (\Exception $e) {
            
        }

        try {
            $this->emptyGreet();
            $this->emptyData();
        } catch (\Exception $e) {
            
        }

        try {
            $this->userActivevalRefresh();
        } catch (\Exception $e) {
            
        }

        //$this->deleteChat();

        /*sleep(10);
        $this->synchUser();

        sleep(10);
        $this->synchUser2();*/
    
        // sleep(10);
        // $this->synchUser3();
    }

    public function bills() {
        try {
            // $this->bill();
            $this->tongjiUser();
            $this->tongjiProxy();
        } catch (\Exception $e) {
            
        }
    }

    public function yesterday()
    {
        $this->checkNoble();
    }
    
    public function halfAnHour()
    {
        $this->moneyTip();
    }
    // 每分钟执行
    public function minutes()
    {
        $min = date('i');
        // 注意：存在时间独占
        // $this->clearUnreplySystemHiChat($min);
        // $this->clearUnreplySystemHiChat2($min);
        // $this->clearUnreplySayHiChat($min);
        // try {
        //     $this->bannedFor230918($min);
        // } catch (\Exception $e) {
        //     Log::write('minutes->bannedFor230918:'.$e->getMessage());
        // }
        try {
            $this->bannedFor230927($min);
            echo 'bannedFor230927 ';
        } catch (\Exception $e) {
            Log::write('minutes->bannedFor230927:'.$e->getMessage());
        }
        try {
            $this->dymanicRefresh($min);
            echo 'dymanicRefresh ';
        } catch (\Exception $e) {
            Log::write('minutes->dymanicRefresh:'.$e->getMessage());
        }
        try {
            $this->ChatFreeOrderCheck();
            echo 'ChatFreeOrderCheck ';
        } catch (\Exception $e) {
            Log::write('minutes->ChatFreeOrderCheck:'.$e->getMessage());
        }
        try {
            $this->checkTopupOrder();
            echo 'checkTopupOrder ';
        } catch (\Exception $e) {
            Log::write('minutes->checkTopupOrder:'.$e->getMessage());
        }
        try {
            $this->checkExpireCoupon();
            echo 'checkExpireCoupon ';
        } catch (\Exception $e) {
            Log::write('minutes->checkExpireCoupon:'.$e->getMessage());
        }
        try {
            $this->checkExpireAddressRedpacket();
            echo 'checkExpireAddressRedpacket ';
        } catch (\Exception $e) {
            Log::write('minutes->checkExpireAddressRedpacket:'.$e->getMessage());
        }
        try {
            $this->checkTimeoutAddressRedpacket();
            echo 'checkTimeoutAddressRedpacket ';
        } catch (\Exception $e) {
            Log::write('minutes->checkTimeoutAddressRedpacket:'.$e->getMessage());
        }
        try {
            $this->checkADorder();
            echo 'checkADorder ';
        } catch (\Exception $e) {
            Log::write('minutes->checkADorder:'.$e->getMessage());
        }
        try {
            $this->clearOnlineState();
            echo 'clearOnlineState ';
        } catch (\Exception $e) {
            Log::write('minutes->clearOnlineState:'.$e->getMessage());
        }
        try {
            $this->clearUserRequestLog();
            echo 'clearUserRequestLog ';
        } catch (\Exception $e) {
            Log::write('minutes->clearUserRequestLog:'.$e->getMessage());
        }
        try {
            $this->clearDuplicateTouristAccount();
            echo 'clearDuplicateTouristAccount ';
        } catch (\Exception $e) {
            Log::write('minutes->clearDuplicateTouristAccount:'.$e->getMessage());
        }
        try {
            $this->setUserQuality();
            echo 'setUserQuality ';
        } catch (\Exception $e) {
            Log::write('minutes->setUserQuality:'.$e->getMessage());
        }
        try {
            $this->checkWarnChat();
            echo 'checkWarnChat ';
        } catch (\Exception $e) {
            Log::write('minutes->checkWarnChat:'.$e->getMessage());
        }
        try {
            $this->clearDyRead($min);
            echo 'clearDyRead ';
        } catch (\Exception $e) {
            Log::write('minutes->clearDyRead:'.$e->getMessage());
        }
        try {
            $this->exceptionUser($min);
            echo 'exceptionUser ';
        } catch (\Exception $e) {
            Log::write('minutes->exceptionUser:'.$e->getMessage());
        }
        // try {
        //     $this->getPayids($min);
        // } catch (\Exception $e) {
        //     Log::write('minutes->getPayids:'.$e->getMessage());
        // }
        try {
            $this->warnUserChatRecordSendCount($min);
            echo 'warnUserChatRecordSendCount ';
        } catch (\Exception $e) {
            Log::write('minutes->warnUserChatRecordSendCount:'.$e->getMessage());
        }

        try {
            $this->checkChatWarnWechat($min);
            echo 'checkChatWarnWechat ';
        } catch (\Exception $e) {
            Log::write('minutes->checkChatWarnWechat:'.$e->getMessage());
        }
        try {
            $this->lianmaiPornoStatis($min);
            echo 'lianmaiPornoStatis ';
        } catch (\Exception $e) {
            Log::write('minutes->lianmaiPornoStatis:'.$e->getMessage());
        }
        try {
            $this->setUserPornoStatis($min);
            echo 'setUserPornoStatis ';
        } catch (\Exception $e) {
            Log::write('minutes->setUserPornoStatis:'.$e->getMessage());
        }
        try {
            $this->setMonthUserPornoStatis($min);
            echo 'setMonthUserPornoStatis ';
        } catch (\Exception $e) {
            Log::write('minutes->setMonthUserPornoStatis:'.$e->getMessage());
        }
        // try {
        //     $this->tongjiPornoed($min);
        //     echo 'tongjiPornoed ';
        // } catch (\Exception $e) {
        //     Log::write('minutes->tongjiPornoed:'.$e->getMessage());
        // }
        try {
            $this->bannedFor20240522($min);
            echo 'bannedFor20240522 ';
        } catch (\Exception $e) {
            Log::write('minutes->bannedFor20240522:'.$e->getMessage());
        }
        try {
            $this->formatDyTitle($min);
            echo 'formatDyTitle ';
        } catch (\Exception $e) {
            Log::write('minutes->formatDyTitle:'.$e->getMessage());
        }
        // $this->setRealnameAuthFail($min);
    }

    public function clearOnlineState()
    {
        $time = date('Y-m-d H:i:s', strtotime('-3 days'));
        $datenow = date('Y-m-d H:i:s');
        try {
            // Db::name('user')->where("is_online=1 and (last_login_datetime<'$time' or (is_banned=1 and banned_end_time>'$datenow'))")->update(['is_online'=>0]);
            $ids = Db::name('user')->where("is_online=1 and (last_login_datetime<'$time' or (is_banned=1 and banned_end_time>'$datenow'))")->limit(10000)->column('id');
            Db::name('user')->where(['id'=>['in', $ids]])->update(['is_online'=>0]);

            // 处理账号到期解冻
            $bannedids = Db::name('user')
                ->where(['is_banned' => 1, 'banned_end_time' => ['elt', date('Y-m-d H:i:s')]])
                ->limit(10000)
                ->column('id');
            if(sizeof($bannedids)){
                $readRules = Db::name('config_personal')->where(['user_id'=>['in',$bannedids], 'is_read_rule'=>1])->column('user_id');
                Db::name('user')->where(['id'=>['in', $readRules]])->update(['is_banned' => 0, 'banned_end_time' => null]);
            }
        } catch (\Exception $e) {
            Log::write('error:clearOnlineState');
        }
    }
    
    private function moneyTip()
    {
        $config = Db::name('config_system')->where(['category' => 'kefu'])->column('title, content');
        
        $kefu = intval($config['id']);

        $uids = Db::name('user')->where(['id' => ['neq', $kefu], 'volley' => ['elt', 5000], 'balance_tip' => 1])->column('id');
        Db::name('user')->where(['id'=>['in', $uids]])->setField('balance_tip', 0);
        
        $where = [
            'id' => ['neq', $kefu],
            'volley' => ['gt', 5000],
            'balance_tip' => 0
        ];

        try {
            $uids = Db::name('user')->where($where)->column('id');
            Db::name('user')->where(['id'=>['in', $uids]])->setField('balance_tip', 1);

            $data = Db::name('user')->where(['id'=>['in', $uids]])->column('phone');
            
            if ($data) {
                $juhe = new Juhe();
                $juhe->send(TimingModel::mobile());
            }
        } catch (\Exception $e) {
            \think\Log::write($e->getMessage());
        }

    }
    
    private function checkOrder()
    {
        $expire_time = time() - 1800;

// $ids = Topup::where(['state' => 0, 'addtime' => ['lt', date('Y-m-d H:i:s', $expire_time)]])->column('id');
// if(sizeof($ids)){
//     Topup::where(['id' => ['in', $ids]])->setField('state', 2);
// }
        $ids = OrderCommon::where(['status' => 0, 'create_time' => ['lt', $expire_time]])->column('id');
        if(sizeof($ids)){
            OrderCommon::where(['id' => ['in', $ids]])->setField('status', -1);
        }
    }
    
    /**
     * 处理未支付充值订单
     */
    private function checkTopupOrder()
    {
        $timenow = time();
        $expire_time = $timenow - 86400;

        $Topups = Db::name('topup')->where(['state' => 0, 'addtime' => ['lt', date('Y-m-d H:i:s', $expire_time)]])->field('id,numbers')->select();
        if(sizeof($Topups)){
            Topup::where(['id' => ['in', array_column($Topups, 'id')]])->setField('state', 2);
            // 返还优惠券
            Db::name('user_coupon')->where(['data'=>['in', array_column($Topups, 'numbers')]])->setField('state', 0);
        }
    }
    
    
    // 用户每日零时账户余额 (00:00)
    private function userBalance()
    {
        $this->tongji_total_amount();
        $date = date('Y-m-d');

        $yesterday_start = strtotime('-30 day', strtotime($date));
        
        Db::name('user_balance')->where(['create_time' => ['lt', $yesterday_start]])->delete();
        
        
        $data = Db::name('user')
                    ->master()
                    ->field('id user_id, volley coin, score')
                    ->where(['sex' => '女', 'role' => 0, 'reg'=>1, 'delete_time'=>0])
                    ->where('score>0 or volley>0')
                    ->select();
    
        if ($data) {
            $current_time = time();
            
            foreach ($data as $key => $item) {
                $data[$key]['date'] = $date;
                $data[$key]['create_time'] = $current_time;
                $data[$key]['update_time'] = $current_time;
            }
    
            Db::name('user_balance')->insertAll($data);
        }
    }

    public function tongji_total_amount()
    {
        $volley = Db::name('user')->where(['delete_time'=>0, 'role'=>0])->sum('volley');
        $score = Db::name('user')->where(['delete_time'=>0, 'role'=>0])->sum('score');
        Db::name('tongji_total_amount')->insert([
            'date'=>date('Y-m-d'),
            'user_volley_all'=>$volley,
            'user_score_all'=>$score,
            'create_time'=>time()
        ]);
    }
    
    // 用户昨日收益
    public function userIncomeYesterday()
    {
        $date = date('Y-m-d');
        $hour = date('H');
        if($hour > 9 || $hour < 3){
            return;
        }

        $yesterday_start = strtotime('-1 day', strtotime($date));
        $yesterday_date = date('Y-m-d', $yesterday_start);
        
        $cache = cache('userIncomeYesterday');
        if($cache){
            return;
        }
        $page = cache('userIncomeYesterdayPage');
        if(!$page){
            $page = 1;
        }
        echo $page;
        $user_ids = Db::name('user_balance')->where(['date' => $yesterday_date])->limit(($page - 1) * 1000, 1000)->column('id, user_id');
        cache('userIncomeYesterdayPage', ++$page, 3600);
        if(sizeof($user_ids) == 0){
            cache('userIncomeYesterday', $date, 3600);
            echo "over";exit;
        }

        if ($user_ids) {
            $startId = Db::name('yaoqing_records')->whereTime('time', $yesterday_date)->cache(43200)->value('id');
            $startId = $startId?:0;
            //$incomes = Db::name('user_data')->where(['user_id' => ['in', $user_ids]])->column('user_id, income_yesterday');
            $incomes = Db::name('yaoqing_records')->where(['id'=>['>=', $startId],'uid' => ['in', $user_ids], 'data' => 0])->whereTime('time', 'between', [$yesterday_date, $yesterday_date.' 23:59:59'])->group('uid')->column('uid, sum(money)');

            $current_time = time();
    
            $contain = [];
            foreach ($user_ids as $key => $item) {
                $contain[] = [
                    'id' => $key,
                    'income' => $incomes[$item] ?? 0,
                    'update_time' => $current_time,
                ];
            }

            (new UserBalance)->saveAll($contain);
        }
    }
    
    // 删除冗余聊天记录
    public function deleteChat()
    {
        $hour = date('H');

        if ($hour >= 18) {
            $limit = 40000;
        } else {
            $limit = 30000;
        }
    
        //Db::name('privatechat')->where(['type' => 8, 'money' => 0, 'addtime' => ['lt', date('Y-m-d H:i:s', strtotime('-1 day'))]])->delete();

        $chat = Db::name('privatechat')->order('id desc')->limit($limit,1)->select();

        if ($chat) {
            $id = $chat[0]['id'];
    
            Db::name('privatechat')->where(['id' => ['lt', $id], 'content' => '对方查看了你的消息'])->delete();


            // $sql = "delete FROM privatechat where id < $id and type=0 and content <> '我在这儿呢' and (userid,touserid)
            // IN
            // (SELECT userid,touserid FROM (SELECT userid,touserid FROM privatechat where id < $id and content <> '我在这儿呢' GROUP BY userid,touserid HAVING COUNT(*)>1 ) s1)
            // AND
            // id NOT IN (SELECT id FROM (SELECT max(id) as id FROM privatechat where id < $id and content <> '我在这儿呢' GROUP BY userid,touserid HAVING COUNT(*)>1) s2)" ;
            
            // Db::execute($sql);

            /*$chat = Db::name('privatechat')->where(['id' => ['lt', $id], 'content' => ['neq', '对方查看了你的消息']])->order('id desc')->select();
    
            $contain1 = [];
            $contain2 = [];
            $del = [];
            foreach ($chat as $key => $item) {
                if (in_array($item['userid'] . '&' . $item['touserid'], $contain1)  || in_array($item['userid'] . '&' . $item['touserid'], $contain2)) {
                    $del[] = $item['id'];
                } else {
                    $contain1[] = $item['userid'] . '&' . $item['touserid'];
                    $contain2[] = $item['touserid'] . '&' . $item['userid'];
                }
            }
            Db::name('privatechat')->where(['id' => ['in', $del]])->delete();*/
        }
    }
    public function deleteChat1()
    {
        Db::name('privatechat')->where(['type' => -1])->delete();
    }
    public function deleteChat2()
    {
        $sql = "delete FROM privatechat where type = 0 and content <> '我在这儿呢' and (userid,content)
            IN
            (SELECT userid,content FROM (SELECT userid,content FROM privatechat where type = 0 and content <> '我在这儿呢' GROUP BY userid,content HAVING COUNT(*)>3 ) s1) limit 20000" ;
        for ($i=0; $i < 10; $i++) { 
            Db::execute($sql);
            sleep(5);
        }

    }
    public function deleteChat3()
    {
        $chat = Db::name('privatechat')->order('id desc')->limit(40000,1)->select();

        if ($chat) {
            $id = $chat[0]['id'];
            $sql = "delete FROM privatechat where id < $id and type=0 and content <> '我在这儿呢' and (userid,touserid)
            IN
            (SELECT userid,touserid FROM (SELECT userid,touserid FROM privatechat where id < $id and content <> '我在这儿呢' GROUP BY userid,touserid HAVING COUNT(*)>1 ) s1)
            AND
            id NOT IN (SELECT id FROM (SELECT max(id) as id FROM privatechat where id < $id and content <> '我在这儿呢' GROUP BY userid,touserid HAVING COUNT(*)>1) s2) limit 20000" ;
                
            for ($i=0; $i < 10; $i++) { 
                Db::execute($sql);
                sleep(5);
            }
        }
    }

    public function deleteChatLists()
    {
        $start_time = strtotime('-1 week');

        $where = ['user_time' => ['lt', $start_time], 'user_first' => 1];
        $whereor = ['another_time' => ['lt', $start_time], 'another_first' => 1];
        Db::name('chat_lists')->where($where)->whereOr(function ($query) use ($whereor) {
            $query->where($whereor);
        })->limit(1000)->delete();
        Db::name('chat_lists')->where(['user_delete' => 1, 'another_delete' => 1])->delete();
    }

    public function mergeWithdraw(){
        $lists = DB::query("SELECT userid,count(*) as count FROM withdraw t1 inner join user t2 on t1.userid=t2.id where t1.state = 0 and t1.channel=1 and t2.delete_time=0 GROUP BY t1.userid");
        $userids = array_column($lists, 'userid');
        $insertArr = [];
        foreach ($lists as $value) {
            $tmplist = Db::name('withdraw')->where(['userid'=>$value['userid'], 'state'=>0, 'channel'=>1])->whereTime('create_time', 'yesterday')->order('id desc')->select();
            $tmp = $tmplist[0];
            if(sizeof($tmplist) > 1){
                for ($i=0; $i < sizeof($tmplist); $i++) {
                    if($i == 0){
                        continue;
                    }
                    $tmp['price'] += $tmplist[$i]['price'];
                    $tmp['shouxu'] += $tmplist[$i]['shouxu'];
                    $tmp['money'] += $tmplist[$i]['money'];
                }
            }
            $tmp['withdraw_ids'] = implode(',',array_column($tmplist, 'id'));
            unset($tmp['id']);
            array_push($insertArr, $tmp);
        }
        // echo "<pre>";
        // var_dump($insertArr);exit;
        // 启动事务
        Db::startTrans();
        try{
            Db::name('withdraw_merge')->insertAll($insertArr);
            // 提交事务
            Db::commit();
            echo "今日共" . sizeof($insertArr) . '人提现';
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            echo "合并失败了";
        }
    }


    public function clearRqlog()
    {
        $ids = Db::name('user_request_log')->order('id', 'desc')->limit(20000)->column('id');
        $res = Db::name('user_request_log')->where(['id'=>['in', $ids]])->delete();
        echo $res;
    }


    public function clearBigRecordTables()
    {
        $hours = date('H');
        if($hours > 20 || $hours < 1){
            return;
        }
        $timenow = time();
        // 活跃度表
        $ids = Db::name('user_activeval_records')->where(['time'=>['<=', $timenow - 60 * 60 * 24 * 3]])->limit(1000)->column('id');
        if(sizeof($ids)){
            Db::name('user_activeval_records')->where(['id'=>['in', $ids]])->delete();
        }

        // 聊天删除任务表
        $ids = Db::name('privatechat_dele_task')->where(['create_time'=>['<=', $timenow - 60 * 60 * 24 * 7]])->limit(1000)->column('id');
        if(sizeof($ids)){
            Db::name('privatechat_dele_task')->where(['id'=>['in', $ids]])->delete();
        }

        // 查看记录表
        $ids = Db::name('see_record')->where('addtime','<= time',$timenow - 60 * 60 * 24 * 10)->limit(1000)->column('id');
        if(sizeof($ids)){
            Db::name('see_record')->where(['id'=>['in', $ids]])->delete();
        }

        // 视频审核记录
        $ids = Db::name('shenhe_task')->where('create_time','<= time',$timenow - 60 * 60 * 24 * 10)->limit(1000)->column('id');
        if(sizeof($ids)){
            Db::name('shenhe_task')->where(['id'=>['in', $ids]])->delete();
        }

        // 失效的服务订单
        $ids = Db::name('order_of_service')->where(['state'=>-1])->where('create_time','<= time',$timenow - 60 * 60 * 24 * 10)->limit(1000)->column('id');
        if(sizeof($ids)){
            Db::name('order_of_service')->where(['id'=>['in', $ids]])->delete();
        }

        // 短信提醒发送记录
        $ids = Db::name('chat_lists_smstip')->where('time','<= time',$timenow - 60 * 60 * 24 * 10)->limit(1000)->column('id');
        if(sizeof($ids)){
            Db::name('chat_lists_smstip')->where(['id'=>['in', $ids]])->delete();
        }
    }



    public function clearDbFiles()
    {
        $list = Db::name('chat_db_files')
                    ->alias('a')
                    ->join('recycle_user b', 'a.user_id=b.user_id')
                    ->column('a.user_id');

        $list = Db::name('user')->where(['id'=>['in', $list], 'delete_time'=>['neq', 0]])->column('id');

        $dblists = Db::name('chat_db_files')->where(['user_id'=>['in', $list]])->select();
        var_dump($dblists);
        foreach ($dblists as $key => $value) {
            $fileinsystempath = ROOT_PATH . $value['path'];
            if(file_exists($fileinsystempath)){
                @unlink($fileinsystempath);
            }
        }
        Db::name('chat_db_files')->where(['id'=>['in', array_column($dblists, 'id')]])->delete();
        $dblists = Db::name('chat_db_files')->master()->where(['user_id'=>['in', $list]])->select();
        var_dump($dblists);
    }


    public function ServiceOrderSettlement()
    {
        $timenow = time();
        $time = $timenow - 1 * 86400;
        $list = Db::name('order_of_service')
            ->where(['paystate' => 1, 'state' => 0, 'status' => 1, 'update_time' => ['<', $time]])
            ->select();
        try {
            Db::name('order_of_service')
                ->where(['paystate' => 0, 'state' => 0, 'status' => 0, 'create_time' => ['<=', $timenow - 30 * 60]])
                ->update(['state' => -1]);
        } catch (\Exception $e) {
            
        }
        $num = 0;
        foreach ($list as $key => $value) {
            $service_commission = $value['commission_rate'];
            $res = Db::name('order_of_service')->where(['id' => $value['id']])->update(['status' => 2]);
            if ($res) {
                $balance         = Db::name('user')->master()->where(['id' => $value['shopowner']])->value('score');
                $money           = $value['price'] * 5 * $service_commission / 100;
                $current_balance = $balance + $money;
                Db::name('user')->where(['id' => $value['shopowner']])->setInc('score', $money);
                Db::name('yaoqing_records')->insert([
                    'uid'      => $value['shopowner'],
                    'touid'    => $value['user_id'],
                    'content'  => '服务订单完成结算',
                    'money'    => $money,
                    'type'     => 1,
                    'data'     => 0,
                    'order_id' => $value['id'],
                    'balance'  => $current_balance,
                    'time'     => time(),
                ]);
                Db::name('privatechat_free')->where(['order_sn' => $value['number']])->update(['end_time' => $timenow]);
                User::fencheng($value['shopowner'], 0, $money, 'service', '服务订单完成');
                \app\api\model\Privatechat::tip($value['user_id'], $value['shopowner'], '本次服务已自动确认完成', json_encode($value, JSON_UNESCAPED_UNICODE), 1, -2);
                $num++;
            }
        }
        echo "本次已处理 $num 个订单";
    }

    // 处理已达标的服务订单
    public function ChatFreeOrderCheck()
    {
        $timenow = time();
        $minute = date('i');
        if ($minute % 5 > 0) {
            return;
        }
        $list = Db::name('privatechat_free')->where(['end_time'=>['>', $timenow], 'confirm'=>0])->select();

        foreach ($list as $key => $value) {
            $lianmaiMinute = $value['audio_second'] + $value['video_second'] > 0 ? ceil(($value['audio_second'] + $value['video_second']) / 60) : 0;
            if ($lianmaiMinute == 0) {
                if ($value['seller_msg'] < 200) {
                    continue;
                }
            } elseif ($lianmaiMinute <= 10) {
                if ($value['seller_msg'] < 150) {
                    continue;
                }
            } elseif ($lianmaiMinute <= 20) {
                if ($value['seller_msg'] < 100) {
                    continue;
                }
            } elseif ($lianmaiMinute <= 30) {
                if ($value['seller_msg'] < 50) {
                    continue;
                }
            } elseif ($lianmaiMinute <= 35) {
                if ($value['seller_msg'] < 0) {
                    continue;
                }
            }
            $order = Db::name('order_of_service')->where(['user_id'=>$value['server']==$value['user_id']?$value['another_id']:$value['user_id'], 'shopowner'=>$value['server'], 'paystate'=>1, 'state'=>0, 'status'=>0])->find();
            if (!$order) {
                continue;
            }
            $res = Db::name('order_of_service')->where(['id' => $order['id']])->update(['status' => 1, 'update_time' => $timenow]);
            if ($res) {

                $userphone = Db::name('user')->where(['id' => $order['user_id']])->value('phone');

                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $order['user_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $order['shopowner']]));
                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $order['user_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/order/orderCount']));
                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $order['shopowner'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $order['user_id']]));

                \app\api\model\Privatechat::tip($order['shopowner'], $order['user_id'], '本次服务已完成，请尽快确认（若不处理，24小时后将自动确认）', json_encode($order, JSON_UNESCAPED_UNICODE), 1, -2);
                \app\api\model\Privatechat::tip($order['user_id'], $order['shopowner'], '本次服务已完成，等待对方确认', '', 1, -1);

                (new \app\api\model\Juhe)->sendTpl($userphone, '249793');
            }
        }
    }

    // 处理过期订单
    public function ChargeMallOrderExpire()
    {
        $this->InsertRedisTPMysqlConnect();
        
        $data = Db::name('mall_order')->where(['status' => 0, 'expire_time' => ['elt', time()]])->order('id desc')->select();
        $ids = array_column($data, 'id');
        $count = sizeof($ids);
        if ($count == 0) {
            return;
        }
        Db::startTrans();
        try {
            foreach ($data as $key => $value) {
                if ($value['des_score'] > 0) {
                    YaoqingRecords::index($value['uid'], 0, $value['des_score'], '订单取消退回 no.' . $value['number'], 1, '', 0);
                }
                if ($value['des_volley'] > 0) {
                    Balance::index($value['uid'], $value['des_volley'], '订单取消退回 no.' . $value['number'], 1);
                }
            }
            Db::name('mall_order')->where(['id' => ['in', $ids]])->setField('status', -3);
            echo "处理 $count 个订单";
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            echo "处理订单失败，操作回退";
        }
    }

    /**
     * 为保持扣费程序的mysql不掉线，外部通过发布订阅触发数据库存活
     * @DateTime 2022-11-10
     */
    private function InsertRedisTPMysqlConnect()
    {
        $minute = date('i');
        if ($minute % 20 == 0) {
            try {
                Cache::store('redis')->set('MYSQL_REFRESH_CONNECT:88888888',time(),10);
            } catch (\Exception $e) {
                // echo $e->getMessage();
            }
        }
    }

    /**
     * Flag提醒打卡
     */
    public function FlagTip()
    {
        $date = date('Y-m-d');
        $time = date('H:i');
        $timenow = time();
        // $time = '11:00';
        Db::name('user_flag')->where(['create_time'=>['<=', $timenow - 30 * 60], 'paystate' => 0, 'status'=>0])->update(['update_time'=>$timenow, 'status' => -1]);
        $data = Db::name('user_flag')->where(['start_date'=>['<=', $date], 'paystate' => 1, 'status'=>0, 'tip_time'=>$time])->select();
        $signed = Db::name('flags')->where(['flag_id'=>['in', array_column($data, 'id')]])->whereTime('create_time', 'today')->column('flag_id');
        $unsignuids = [];
        foreach ($data as $value) {
            if (!in_array($value['id'], $signed)) {
                $unsignuids[] = $value['user_id'];
            }
        }
        $users = Db::name('user')->where(['id'=>['in', $unsignuids]])->column('phone');
        foreach ($users as $value) {
            if ($users) {
                try {
                    (new Juhe)->sendTpl($value, '250632');
                } catch (\Exception $e) {
                    
                }
            }
        }
        return $this->pass($unsignuids);
    }

    /**
     * Flag过期挑战失败
     */
    public function FlagExpire()
    {
        $timenow = time();
        $data = Db::name('user_flag')->where(['end_time'=>['<=', $timenow], 'paystate' => 1, 'status'=>0])->select();
        if (sizeof($data) == 0) {
            return;
        }
        $inserts = [];
        foreach ($data as $key => $value) {
            if ($value['price'] > 0) {
                $inserts[] = [
                    'flag_id' => $value['id'],
                    'price' => $value['price'],
                    'score' => $value['price'] * 5,
                    'create_time'=>$timenow
                ];
            }
        }
        if (sizeof($inserts)) {
            Db::name('flag_expire')->insertAll($inserts);
        }
        Db::name('user_flag')->where(['id'=>['in', array_column($data, 'id')]])->update(['update_time' => $timenow, 'status' => -1]);
    }

    /**
     * Flag瓜分激励金
     */
    public function FlagExpireGrant()
    {
        $hours = date('H');
        if($hours > 20 || $hours < 1){
            return;
        }
        $timenow = time();
        $config = Config::where(['category' => 'flag'])->column('title, content');
        $data = Db::name('flag_expire')->where(['state'=>0])->limit(50)->select();
        foreach ($data as $key => $value) {
            $flagInfo = Db::name('user_flag')->find($value['flag_id']);
            $supervise = Db::name('flag_supervise')->where(['flag_id'=>$value['flag_id']])->field('id,user_id,copies')->select();
            $len = Db::name('flag_supervise')->where(['flag_id'=>$value['flag_id']])->sum('copies');
            if ($len) {
                $score = round($value['score'] * $config['flag_rate'] / $len, 2);
                $success = [];
                foreach ($supervise as $k => $v) {
                    try {
                        YaoqingRecords::index($v['user_id'], 0, round($score * $v['copies'], 2), '围观Flag 【ID: ' . $flagInfo['id'] . '】【' . $flagInfo['content'] . '】 所得激励金 ', 1);
                        Privatechat::notice($v['user_id'], '您围观的Flag【' . $flagInfo['content'] . '】坚持打卡失败，瓜分激励金所得 '. round($score * $v['copies'], 2) .' 积分已转入您的账户');
                        $success[] = $v['id'];
                    } catch (\Exception $e) {
                        
                    }
                }
                Db::name('flag_supervise')->where(['id'=>['in', $success], 'copies'=>1])->update(['score'=>$score, 'state'=>1]);
                Db::name('flag_supervise')->where(['id'=>['in', $success], 'copies'=>3])->update(['score'=>round($score * 3, 2), 'state'=>1]);
            }
            Db::name('flag_expire')->where(['id'=>$value['id']])->update(['state'=>1, 'update_time'=>$timenow]);
        }
    }

    /**
     * 处理失效优惠券
     */
    private function checkExpireCoupon()
    {
        $timenow = time();
        $data = Db::name('user_coupon')->where(['state' => 0, 'expire_time' => ['<=', $timenow]])->column('id');
        if ($len = sizeof($data)) {
            Db::name('user_coupon')->where(['id' => ['in', $data]])->setField('state', -1);
            echo '失效 ' . $len . ' 张优惠券';
        }
    }

    /**
     * 处理失效地点红包
     */
    private function checkExpireAddressRedpacket()
    {
        $timenow = time();
        $data = Db::name('user_address_red_packet')->where(['status' => 0, 'paystate' => 1, 'expire_time' => ['<=', $timenow]])->column('id');
        if ($len = sizeof($data)) {
            Db::name('user_address_red_packet')->where(['id' => ['in', $data]])->setField('status', -1);
            echo '失效 ' . $len . ' 批地点红包';
        }
    }

    /**
     * 处理超时未支付地点红包
     */
    private function checkTimeoutAddressRedpacket()
    {
        $timenow = time();
        $data = Db::name('user_address_red_packet')->where(['status' => 0, 'paystate' => 0, 'create_time' => ['<=', $timenow - 900]])->column('id');
        if ($len = sizeof($data)) {
            Db::name('user_address_red_packet')->where(['id' => ['in', $data]])->update(['paystate' => -1, 'status' => -1]);
            echo $len . ' 批地点红包支付超时';
        }
    }

    public function everydayunfrozen()
    {
        $timenow = time();
        $todaystart = strtotime(date('Y-m-d'));
        $data = Db::name('wallet_frozen')->where(['value' => ['>', 0], 'everyday_unfrozen' => ['>', 0], 'auto_time' => ['<', $todaystart]])->select();
        $num = 0;
        foreach ($data as $key => $value) {
            if ($value['value'] > $value['everyday_unfrozen']) {
                $dec = $value['everyday_unfrozen'];
                $next = $value['everyday_unfrozen'];
            } else {
                $dec = $value['value'];
                $next = 0;
            }
            Db::name('wallet_frozen')->where('id', $value['id'])->update(['value' => Db::raw("value - $dec"), 'auto_time' => $timenow, 'everyday_unfrozen' => $next]);
            Db::name('wallet_frozen_records')->insert(['user_id'=>$value['user_id'], 'value'=>$dec, 'time'=>$timenow,'type'=>1,'remark'=>'系统自动解冻']);
            $num++;
        }
        if ($num > 0) {
            echo "处理 $num 个自动解冻";
        }

        $this->tongjiPayment();
        $this->tongjiUserData();
        $this->tongJIDynamic();
    }

    /**
     * 处理地点订单
     */
    public function checkADorder()
    {
        $timenow = time();
        $expires = Db::name('order_of_addressgood')->where(['expire_time' => ['<', $timenow], 'status' => 0, 'paystate' => 1])->select();
        if (sizeof($expires)) {
            Db::name('order_of_addressgood')->where(['id' => ['in', array_column($expires, 'id')]])->update(['status' => -1]);
            foreach ($expires as $key => $value) {
                YaoqingRecords::index($value['user_id'], 0, $value['price'] * 5, '店铺订单取消退回 no.' . $value['number'], 1, '', 0);
            }
        }
        $data = Db::name('order_of_addressgood')->where(['create_time' => ['<', $timenow - 900], 'paystate' => 0])->select();
        $ids = array_column($data, 'id');
        $coupon_ids = array_column($data, 'coupon_id');
        $coupon_ids = array_unique(array_filter(explode(',', implode(',', $coupon_ids))));
        if (sizeof($expires)) {
            $coupon_ids = array_merge($coupon_ids, array_unique(array_filter(explode(',', implode(',', array_column($data, 'coupon_id'))))));
        }
        $stocks = [];
        foreach ($data as $value) {
            if (isset($stocks[$value['good_id']])) {
                $stocks[$value['good_id']] += $value['num'];
            } else {
                $stocks[$value['good_id']] = $value['num'];
            }
        }
        foreach ($stocks as $key => $value) {
            Db::name('user_address_goods')->where(['id'=>$key])->setInc('stock', $value);
        }
        if (sizeof($ids)) {
            Db::name('order_of_addressgood')->where(['id'=>['in',$ids]])->update(['status' => -1, 'paystate' => -1]);
            if (sizeof($coupon_ids)) {
                Db::name('user_coupon')->where(['id'=>['in',$coupon_ids]])->setField('state', 0);
            }
        }
    }

    // 每日凌晨1点40更新用户本月收益（计算昨日收益并入本月收益中）
    public function userData1()
    {
        $incomes = Db::name('yaoqing_records')->where(['data' => 0])->whereNotLike('content','%提现%')->whereTime('time', 'yesterday')->group('uid')->fetchSql(false)->column('uid, sum(money)');
        // var_dump($incomes);exit;
        foreach ($incomes as $key => $item) {
            Db::name('user_data')->where(['user_id'=>$key])->setInc('income_month', $item);
        }
    }
    // 每月初凌晨2点10更新用户上月收益,并且清除本月收益
    public function userData2()
    {
        $incomes = Db::name('user_data')->where(['income_month' => ['>', 0]])->column('id, income_month');
        foreach ($incomes as $key => $item) {
            Db::name('user_data')->where(['id'=>$key])->update(['income_last_month' => $item, 'income_month' => 0]);
        }
    }
    // 每月初凌晨2点更新用户上月充值
    public function userData3()
    {
        Db::name('user_data')->where(['topup_last_month'=>['>', 0]])->update(['topup_last_month'=>0]);
        $recharges = Db::name('topup')->where(['state' => 1])->whereTime('addtime', 'last month')->group('fk_userid')->column('fk_userid, sum(money)');
        $inserts = [];
        foreach ($recharges as $key => $item) {
            $res = Db::name('user_data')->where(['user_id'=>$key])->update(['topup_last_month'=>$item]);
            if (!$res) {
                $inserts[] = ['user_id'=>$key, 'topup_last_month'=>$item];
            }
        }
        try {
            Db::name('user_data')->insertAll($inserts);
        } catch (\Exception $e) {
            
        }
    }
    // 每月初凌晨1点开始更新用户团队信息
    public function updateUserTeam1()
    {
        $day = date('d');
        $hour = date('H');
        if($day > 1 || $hour > 9 || $hour < 1){
            return;
        }
        $timenow = time();
        $lastid = cache('updateUserTeamlastid');
        $lastid = $lastid ?? 0;
        $notin = Db::name('user_team')->whereTime('team_update_time', 'today')->column('user_id');
        $users = Db::name('user')->where(['id'=>['not in', $notin], 'id'=>['>', $lastid], 'delete_time' => 0])->where('yqm','not null')->limit(1000)->column('id, yqm');

        $inserts = [];
        foreach ($users as $key => $value) {
            // 一级徒弟
            $one = Db::name('user')->where(['yqr'=>$value])->column('id, yqm');
            // 二级徒弟
            if (sizeof($one)) {
                $two = Db::name('user')->where(['yqr'=>['in', array_values($one)]])->column('id, yqm');
            } else {
                $two = [];
            }
            // 三级徒弟
            if (sizeof($two)) {
                $three = Db::name('user')->where(['yqr'=>['in', array_values($two)]])->column('id, yqm');
            } else {
                $three = [];
            }
            $ones = implode(',',array_keys($one));
            $twos = implode(',',array_keys($two));
            $threes = implode(',',array_keys($three));
            $has = Db::name('user_team')->where(['user_id'=>$key])->find();
            if ($has) {
                Db::name('user_team')->where(['id'=>$has['id']])->update([
                    'one'=>$ones,
                    'two'=>$twos,
                    'three'=>$threes,
                    'team_update_time'=>$timenow
                ]);
            } else {
                if (sizeof($one)) {
                    $inserts[] = [
                        'user_id'=>$key,
                        'one'=>$ones,
                        'two'=>$twos,
                        'three'=>$threes,
                        'team_update_time'=>$timenow
                    ];
                }
            }
            $lastid = $key;
        }
        if (sizeof($inserts)) {
            Db::name('user_team')->insertAll($inserts);
        }
        cache('updateUserTeamlastid', $lastid, 600);
    }

    // 每月初凌晨2点开始更新用户团队数据
    public function updateUserTeam2()
    {
        $day = date('d');
        $hour = date('H');
        if($day > 1 || $hour > 9 || $hour < 3){
            return;
        }
        $timenow = time();
        $todaystart = strtotime(date('Y-m-d'));
        $teams = Db::name('user_team')->where(['team_update_time'=>['>=', $todaystart], 'date_update_time'=>['<', $todaystart]])->limit(1000)->field('id,user_id,one,two,three')->select();
        $contain = [];
        foreach ($teams as $key => $value) {
            $one = Db::name('user_data')->where(['user_id'=>['in', $value['one']]])->field('sum(income_last_month) income_last_month,sum(topup_last_month) topup_last_month')->find();
            if ($value['two']) {
                $two = Db::name('user_data')->where(['user_id'=>['in', $value['two']]])->field('sum(income_last_month) income_last_month,sum(topup_last_month) topup_last_month')->find();
            } else {
                $two = ['income_last_month'=>0, 'topup_last_month'=>0];
            }
            if ($value['three']) {
                $three = Db::name('user_data')->where(['user_id'=>['in', $value['three']]])->field('sum(income_last_month) income_last_month,sum(topup_last_month) topup_last_month')->find();
            } else {
                $three = ['income_last_month'=>0, 'topup_last_month'=>0];
            }
            $content = [
                'id' => $value['id'],
                'one_shouyi_last_month' => $one['income_last_month'] ?? 0,
                'one_recharge_last_month' => $one['topup_last_month'] ?? 0,
                'two_shouyi_last_month' => $two['income_last_month'] ?? 0,
                'two_recharge_last_month' => $two['topup_last_month'] ?? 0,
                'three_shouyi_last_month' => $three['income_last_month'] ?? 0,
                'three_recharge_last_month' => $three['topup_last_month'] ?? 0,
                'date_update_time'  => $timenow
            ];
            $content['total_shouyi_last_month'] = $content['one_shouyi_last_month'] + $content['two_shouyi_last_month'] + $content['three_shouyi_last_month'];
            $content['total_recharge_last_month'] = $content['one_recharge_last_month'] + $content['two_recharge_last_month'] + $content['three_recharge_last_month'];
            $contain[] = $content;
        }
        (new UserTeam)->saveAll($contain);
    }

    public function checkActivityOrders()
    {
        $timenow = time();
        $data = Db::name('activity_join')->where(['paystate'=>1,'state'=>0,'end_time'=>['<=', $timenow]])->select();
        if (sizeof($data) == 0) {
            return;
        }
        $actives = Db::name('activity_offline')->where(['id'=>['in', array_column($data, 'active_id')]])->column('*','id');
        foreach ($data as $key => $value) {
            Db::name('activity_join')->where(['id'=>$value['id']])->update(['state'=>1,'update_time'=>$timenow]);
            if ($value['price'] > 0) {
                YaoqingRecords::index($actives[$value['active_id']]['user_id'], $value['user_id'], $value['price'] * 5, '活动【' . $actives[$value['active_id']]['content'] . '】报名款', 1);
            }
        }
    }

    public function userQuality()
    {
        $users = Db::name('user')
                    ->alias('a')
                    ->join('user_punish b', 'a.id=b.user_id', 'left')
                    ->where(['a.phone' => ['not in', ['', null]], 'a.delete_time' => 0, 'a.sex' => '女', 'b.id'=>Db::raw('is null')])
                    ->limit(1000)
                    ->order('a.id asc')
                    ->field('a.id,a.activeval,a.banned_end_time,a.shouyi,a.quality')
                    ->select();
        $userids = array_column($users, 'id');
        $limit_age_user_ids = Db::name('change_age_limit')->where(['user_id'=>['in', $userids]])->column('user_id');
        $withdraw_limit_user_ids = Db::name('withdraw_limit')->where(['user_id'=>['in', $userids]])->column('user_id');
        $wallet_frozen_records_user_ids = Db::name('wallet_frozen_records')->where(['user_id'=>['in', $userids]])->column('user_id');
        $search_limit_user_ids = Db::name('search_limit')->where(['user_id'=>['in', $userids]])->column('user_id');
        $user_warn_user_ids = Db::name('user_warn')->where(['user_id'=>['in', $userids]])->column('user_id');
        $user_warn_records_user_ids = Db::name('user_warn_records')->where(['user_id'=>['in', $userids]])->column('user_id');
        $report_user_user_ids = Db::name('report_user')->where(['report_user'=>['in', $userids]])->column('report_user');
        $inserts = [];
        foreach ($users as $key => $value) {
            $inserts[] = [
                'user_id' => $value['id'],
                'age_limit' => in_array($value['id'], $limit_age_user_ids) ? 1 : 0,
                'withdraw_limit' => in_array($value['id'], $withdraw_limit_user_ids) ? 1 : 0,
                'wallet_frozen' => in_array($value['id'], $wallet_frozen_records_user_ids) ? 1 : 0,
                'search_limit' => in_array($value['id'], $search_limit_user_ids) ? 1 : 0,
                'banned' => $value['banned_end_time'] ? 1 : 0,
                'warn_monitor' => in_array($value['id'], $user_warn_records_user_ids) ? 1 : 0,
                'complaint' => in_array($value['id'], $report_user_user_ids) ? 1 : 0,
            ];
        }
        Db::name('user_punish')->insertAll($inserts);
        foreach ($inserts as $key => $value) {
            UserPunish::userQuality($value['user_id']);
        }
    }


    /**
     * 游客用户每天请一次（每个设备只保留一个游客用户）
     * @DateTime 2023-01-28
     */
    private function clearDuplicateTouristAccount()
    {
        if (cache('clearDuplicateTouristAccount')) {
            return;
        }
        $data = Db::name('user')->group('device_id')->field('id, device_id, count(device_id) device_id_count')->where(['reg' => 0])->order('device_id_count desc')->select();
        $user = [];
        foreach ($data as $key => $value) {
            if ($value['device_id_count'] > 2) {
                $over = Db::name('user')->where(['device_id' => $value['device_id'], 'id' => ['>', $value['id']], 'reg' => 0])->column('id');
                $user = array_merge($user, $over);
            } else {
                break;
            }
        }
        $user = Db::name('user')->where(['id'=>['in', $user], 'reg' => 0])->column('id');
        Db::name('user')->where(['id'=>['in', $user]])->delete();

        cache('clearDuplicateTouristAccount', '99999', 86400);
    }

    private function clearUserRequestLog()
    {
        if (cache('clearUserRequestLog')) {
            return;
        }
        $timenow = time();
        $logs = Db::name('user_request_log')->where('time','<= time',$timenow - 7 * 60 * 60 * 24)->limit(10000)->column('id');
        if (sizeof($logs)) {
            Db::name('user_request_log')->where(['id' => ['in', $logs]])->delete();
        }

        cache('clearUserRequestLog', $timenow, 50);
    }

    private function setUserQuality()
    {
        if (cache('setUserQuality')) {
            return;
        }
        $timenow = time();
        $overprice = Db::name('config_personal')
                        ->whereOr(['chat_price' => ['>=', 5], 'voice_price' => ['>=', 35], 'video_price' => ['>=', 50]])
                        ->column('user_id');
        $data = Db::name('user')->where(['id'=>['in', $overprice], 'quality'=>['<>', 1]])->limit(10000)->column('quality','id');
        try {
            Db::name('user')->where(['id'=>['in', array_keys($data)]])->update(['quality' => 1]);
            $inserts = [];
            $qualitys = ['未检出','低端','一般','优质','超优质'];
            foreach ($data as $key => $value) {
                $text = '用户费用超高，变更用户质量：'.$qualitys[$value].'=>'.$qualitys[1];
                $inserts[] = ['channel'=>3,'admin'=>'系统','user_id'=>$key,'content'=>$text];
            }
            if (sizeof($inserts)) {
                Db::name('admin_logs')->insert($inserts);
            }
        } catch (\Exception $e) {
            
        }
        // try {
        //     Db::name('user')->where(['noble_grade' => ['>', 0], 'noble_time' => ['>' , $timenow]])->update(['quality' => 4]);
        // } catch (\Exception $e) {
            
        // }
        cache('setUserQuality', $timenow, 3600);
    }

    public function checkUserInviteRecords()
    {
        $data = Db::name('user_invite_records')->where(['state'=>0, 'score'=>['>', 0]])->whereTime('create_time', '-7 days')->select();
        $activeUids = Db::name('user_data')->where(['user_id'=>['in', array_column($data, 'touserid')]])->where('topup>0 or income>2')->column('user_id');
        $updateIds = [];
        foreach ($data as $key => $value) {
            if (in_array($value['touserid'], $activeUids)) {
                try {
                    YaoqingRecords::index($value['user_id'], $value['touserid'], $value['score'], '邀请奖励', 1);
                    $updateIds[] = $value['id'];
                } catch (\Exception $e) {
                    
                }
            }
        }
        if (sizeof($updateIds)) {
            Db::name('user_invite_records')->where(['id'=>['in', $updateIds]])->update(['state'=>1]);
        }
    }

    public function tongjiPayment($date = '', $return = false)
    {
        $date = $date ? $date : date('Y-m-d', strtotime('-1 day'));
        $time = strtotime($date);

        $data = Db::name('tongji_payments')->where(['date'=>$date])->find();
        if ($data) {
            if ($return) {
                return $data;
            }
            return;
        }

        $recharge_wechat = Db::name('topup')
                            ->where(['type'=>0,'state'=>1])
                            ->whereTime('addtime', 'between', [$date . ' 00:00:00', $date . ' 23:59:59'])
                            ->select();
        $recharge_wechat_count = sizeof($recharge_wechat);
        $recharge_wechat_sum_price = array_sum(array_column($recharge_wechat, 'price'));
        $recharge_wechat_sum_volley = array_sum(array_column($recharge_wechat, 'money'));

        $recharge_alipay = Db::name('topup')
                            ->where(['type'=>1,'state'=>1])
                            ->whereTime('addtime', 'between', [$date . ' 00:00:00', $date . ' 23:59:59'])
                            ->select();
        $recharge_alipay_count = sizeof($recharge_alipay);
        $recharge_alipay_sum_price = array_sum(array_column($recharge_alipay, 'price'));
        $recharge_alipay_sum_volley = array_sum(array_column($recharge_alipay, 'money'));

        $recharge_sum_price = $recharge_alipay_sum_price + $recharge_wechat_sum_price;
        $recharge_sum_volley = $recharge_alipay_sum_volley + $recharge_wechat_sum_volley;
        $recharge_count = $recharge_wechat_count ? $recharge_alipay_count + $recharge_wechat_count : 0;
        $recharge_avg_price = $recharge_count ? $recharge_sum_price / $recharge_count : 0;
        
        // 系统入账总额
        $income_volley_sum = Db::name('volley_desc')->where(['types'=>1])->whereTime('time', 'between', [$date . ' 00:00:00', $date . ' 23:59:59'])->sum('price');
        // 金币消耗
        $consume_volley_sum = Db::name('volley_desc')->where(['types'=>0])->whereTime('time', 'between', [$date . ' 00:00:00', $date . ' 23:59:59'])->sum('price');
        // 未回复返回
        $refund_sum = Db::name('volley_desc')->where(['content'=>['like', '%未回复消息，过期返还金币']])->whereTime('time', 'between', [$date . ' 00:00:00', $date . ' 23:59:59'])->sum('price');
        // 实际消费金币
        $real_consume_volley_sum = $consume_volley_sum - $refund_sum;
        // 充值注销账号人数
        $recycle_count = Db::name('recycle_review')->where(['user_id'=>['in', array_merge(array_column($recharge_wechat, 'fk_userid'), array_column($recharge_alipay, 'fk_userid'))]])->whereTime('create_time', 'between', [$date . ' 00:00:00', $date . ' 23:59:59'])->count();
        // 充值实际上赠送积分
        $recharge_give_score = Db::name('yaoqing_records')->where(['data'=>0,'content'=>['like','%充值%']])->whereTime('time', 'between', [$date . ' 00:00:00', $date . ' 23:59:59'])->sum('money');
        // 系统入账积分
        $income_score_sum = Db::name('yaoqing_records')->where(['data'=>0])->whereTime('time', 'between', [$date . ' 00:00:00', $date . ' 23:59:59'])->sum('money');
        // 提现回退积分
        $refund_score_sum = Db::name('yaoqing_records')->where(['data'=>0, 'content'=>['like', '%提现%']])->whereTime('time', 'between', [$date . ' 00:00:00', $date . ' 23:59:59'])->sum('money');
        // 消费积分总额
        $consume_score_sum = Db::name('yaoqing_records')->where(['data'=>1])->whereTime('time', 'between', [$date . ' 00:00:00', $date . ' 23:59:59'])->sum('money');
        // 后台充金币
        $admin_recharge_volley = Db::name('customer_service_userup')->where(['toward'=>1, 'channel'=>1])->whereTime('update_time', 'between', [strtotime($date . ' 00:00:00'), strtotime($date . ' 23:59:59')])->sum('money');
        // 金币差值
        $differ_volley_sum = $income_volley_sum - $recharge_sum_volley - $admin_recharge_volley;

        // 系统总剩余金币
        $user_volley_all = Db::name('tongji_total_amount')
                                ->where(['date'=>date('Y-m-d', strtotime($date) + 86400)])
                                ->value('user_volley_all');
        $user_volley_all = $user_volley_all ?: 0;

        // 前一天系统总剩余金币
        $user_volley_all_prev = Db::name('tongji_total_amount')
                                ->where(['date'=>$date])
                                ->value('user_volley_all');
        $user_volley_all_prev = $user_volley_all_prev ?: 0;
        // 实际消耗
        $real_consume_volley = $user_volley_all_prev + $income_volley_sum - $user_volley_all;
        // 充值理论上赠送积分
        $topup_all = array_merge($recharge_wechat, $recharge_alipay);
        $topup_all_user = [];
        foreach ($topup_all as $key => $value) {
            if(!isset($topup_all_user[$value['fk_userid']])) {
                $topup_all_user[$value['fk_userid']] = 0;
            }
            $topup_all_user[$value['fk_userid']] += $value['money'];
        }
        // 充值理论上赠送积分
        $recharge_give_score = 0;
        foreach ($topup_all_user as $key => $value) {
            $i = 0;
            $yqm = $key;
            while ($i < 3) {
                $yqr = Db::name('user')->where(['id'=>$yqm, 'delete_time'=>0, 'is_banned'=>0])->value('yqr');
                if ($yqr) {
                    $yqr = Db::name('user')->where(['yqm'=>$yqr])->field('id,yqr')->find();
                    $team = Db::name('user_team')->where(['user_id'=>$yqr['id']])->field('one,two,three')->find();

                    $performance = 0;
                    if ($team) {
                        $team_ids = implode(',', [$team['one'],$team['two'],$team['three']]);
                        if ($team_ids) {
                            $performance = Db::name('user_data')->where(['user_id' => ['in', $team_ids]])->sum('topup');
                        }
                    }
                    $configInvite = Db::name('config_invite')->where(['types' => 2, 'min' => ['elt', $performance]])->order('min desc')->find();

                    $recharge_give_score += $configInvite['income'] * $value;
                    if ($yqr['yqr']) {
                        $yqm = $yqr['yqr'];
                        $i++;
                    } else {
                        $i = 3;
                    }
                } else {
                    $i = 3;
                }
            }
        }
        // 消费理论上产生积分
        // $yaoqing_records_getscore_touids = Db::name('yaoqing_records')
        //                              ->where(function ($query)
        //                              {
        //                                  $query->where(['content'=>['like','%消息获得积分收益%']])->whereOr(['content'=>['like','%通话收益%']]);
        //                              })
        //                              ->whereTime('time', 'between', [$date . ' 00:00:00', $date . ' 23:59:59'])
        //                              ->group('touid')
        //                              ->column('touid');
        // $yaoqing_records_getscore_touids = array_slice($yaoqing_records_getscore_touids, 0, 50);
        // $consume_volley_all_user = Db::name('volley_desc')
        //                              ->where(['types'=>0, 'user_id'=>['in', $yaoqing_records_getscore_touids]])
        //                              ->whereTime('time', 'between', [$date . ' 00:00:00', $date . ' 23:59:59'])
        //                              ->group('user_id')
        //                              ->field('user_id, sum(price) as price');
        $consume_give_score = ($real_consume_volley_sum*0.57)*(0.225+0.07+0.03)+$real_consume_volley_sum*0.57;
        // 过往充值补积分
        $recharge_makeup_score = Db::name('yaoqing_records')->where(['data'=>0, 'content'=>['like', '%绑定提成补发']])->whereTime('time', 'between', [$date . ' 00:00:00', $date . ' 23:59:59'])->sum('money');
        $sum_score = $recharge_give_score + $consume_give_score;
        // 理论与实际积分差值
        $diff_real_score = $sum_score + $recharge_makeup_score - ($income_score_sum - $refund_score_sum);
        // 总提现金额
        $withdraw_records = Db::name('withdraw')->whereTime('create_time', 'between', [$date . ' 00:00:00', $date . ' 23:59:59'])->field('price,shouxu,money')->select();
        $withdraw_records_money = array_sum(array_column($withdraw_records, 'money'));
        // 提现理论积分
        $withdraw_records_money_cn = $withdraw_records_money * 5.15;
        // 总提现积分
        $withdraw_records_money_en = array_sum(array_column($withdraw_records, 'price')) + array_sum(array_column($withdraw_records, 'shouxu'));
        // 剩余总积分
        $user_score_all = Db::name('tongji_total_amount')
                                ->where(['date'=>date('Y-m-d', strtotime($date) + 86400)])
                                ->value('user_score_all');
        $user_score_all = $user_score_all ?: 0;
        // 前一天系统总剩余积分
        $user_score_all_prev = Db::name('tongji_total_amount')
                                ->where(['date'=>$date])
                                ->value('user_score_all');
        $user_score_all_prev = $user_score_all_prev ?: 0;
        // 实际消耗
        $real_consume_score = $user_score_all_prev + $income_volley_sum - $user_score_all;
        // 实际可提现比率
        $rate_withdraw = $withdraw_records_money_en ? ($withdraw_records_money * 5) / $withdraw_records_money_en : 0.97;
        // 利润率
        $lirun = $recharge_sum_volley ? 1-(($income_score_sum - $refund_score_sum)*$rate_withdraw)/$recharge_sum_volley : 0;
        // echo "<pre>";
        // print_r($lirun);
        $recharge_admin = 0;
        $income_volley_over_sum = 0;
        $refund_volley_sum = 0;
        $system_gift_volley_2 = Db::name('volley_desc')->where(['types'=>1, 'price'=>['<', 50]])->whereTime('time', 'between', [$date . ' 00:00:00', $date . ' 23:59:59'])->sum('price');
        // 估算实送
        $system_gift_volley = $system_gift_volley_2 - $refund_sum;
        $month_lirun = 0;
        $last30day = Db::name('tongji_payments')->whereTime('create_time','-29 days')->where(['lirun'=>['<>', 0]])->field('id,month_lirun')->select();
        $lastLen = sizeof($last30day);
        if ($lastLen) {
            $month_lirun = (array_sum(array_column($last30day, 'month_lirun')) + $lirun) / ($lastLen + 1);
        }

        $user_score_all_cn = $income_score_sum + $user_score_all_prev - $withdraw_records_money_en;

        $vip_order_wechat  = Db::name('order_common')->where(['types'=>6, 'status'=>1, 'pays'=>3])->whereTime('update_time', 'between', [strtotime($date . ' 00:00:00'), strtotime($date . ' 23:59:59')])->column('money');
        $vip_order_wechat_money  = array_sum($vip_order_wechat);
        $vip_order_wechat_num  = sizeof($vip_order_wechat);
        $vip_order_alipay  = Db::name('order_common')->where(['types'=>6, 'status'=>1, 'pays'=>2])->whereTime('update_time', 'between', [strtotime($date . ' 00:00:00'), strtotime($date . ' 23:59:59')])->column('money');
        $vip_order_alipay_money  = array_sum($vip_order_alipay);
        $vip_order_alipay_num  = sizeof($vip_order_alipay);

        $flag_order_wechat  = Db::name('user_flag')->where(['price'=>['>',0], 'paystate'=>1, 'paymethod'=>3])->whereTime('create_time', 'between', [strtotime($date . ' 00:00:00'), strtotime($date . ' 23:59:59')])->column('price');
        $flag_order_wechat_money  = array_sum($flag_order_wechat);
        $flag_order_wechat_num  = sizeof($flag_order_wechat);
        $flag_order_alipay  = Db::name('user_flag')->where(['price'=>['>',0], 'paystate'=>1, 'paymethod'=>2])->whereTime('create_time', 'between', [strtotime($date . ' 00:00:00'), strtotime($date . ' 23:59:59')])->column('price');
        $flag_order_alipay_money  = array_sum($flag_order_alipay);
        $flag_order_alipay_num  = sizeof($flag_order_alipay);


        $data = [
            'recharge_wechat_count'=>$recharge_wechat_count,
            'recharge_wechat_sum_price'=>$recharge_wechat_sum_price,
            'recharge_alipay_count'=>$recharge_alipay_count,
            'recharge_alipay_sum_price'=>$recharge_alipay_sum_price,
            'recharge_sum_price'=>$recharge_sum_price,
            'recharge_sum_volley'=>$recharge_sum_volley,
            'recharge_count'=>$recharge_count,
            'recharge_rate'=>$recharge_sum_price ? $recharge_sum_volley/$recharge_sum_price : 0,
            'recharge_avg_price'=>$recharge_avg_price,
            'income_volley_sum'=>$income_volley_sum,
            'user_volley_all'=>$user_volley_all,
            'user_volley_all_prev'=>$user_volley_all_prev,
            'differ_volley_sum'=>$differ_volley_sum,
            'system_gift_volley'=>$system_gift_volley,
            'refund_sum'=>$refund_sum,
            'real_consume_volley'=>$real_consume_volley,
            'income_score_sum'=>$income_score_sum,
            'refund_score_sum'=>$refund_score_sum,
            'recycle_count'=>$recycle_count,
            'recharge_give_score'=>$recharge_give_score,
            'consume_give_score'=>$consume_give_score,
            'sum_score'=>$sum_score,
            'recharge_makeup_score'=>$recharge_makeup_score,
            'consume_volley_sum'=>$consume_volley_sum,
            'real_consume_volley_sum'=>$real_consume_volley_sum,
            'diff_real_score'=>$diff_real_score,
            'withdraw_records_money'=>$withdraw_records_money,
            'withdraw_records_money_cn'=>$withdraw_records_money_cn,
            'withdraw_records_money_en'=>$withdraw_records_money_en,
            'real_consume_score'=>$real_consume_score,
            'lirun'=>$lirun,
            'user_score_all'=>$user_score_all,
            'user_score_all_prev'=>$user_score_all_prev,
            'recharge_admin'=>$recharge_admin,
            'income_volley_over_sum'=>$income_volley_over_sum,
            'refund_volley_sum'=>$refund_volley_sum,
            'system_gift_volley_2'=>$system_gift_volley_2,
            'month_lirun'=>$month_lirun,
            'user_score_all_cn'=>$user_score_all_cn,
            'vip_order_wechat_money'=>$vip_order_wechat_money,
            'vip_order_wechat_num'=>$vip_order_wechat_num,
            'vip_order_alipay_money'=>$vip_order_alipay_money,
            'vip_order_alipay_num'=>$vip_order_alipay_num,
            'flag_order_wechat_money'=>$flag_order_wechat_money,
            'flag_order_wechat_num'=>$flag_order_wechat_num,
            'flag_order_alipay_money'=>$flag_order_alipay_money,
            'flag_order_alipay_num'=>$flag_order_alipay_num,
            'admin_recharge_volley'=>$admin_recharge_volley
        ];
        if (strtotime($date) < strtotime(date('Y-m-d'))) {
            $data['date'] = $date;
            $data['create_time'] = time();
            Db::name('tongji_payments')->insert($data);
        }
        if ($return) {
            return $data;
        }
    }


    public function dymanicRefresh($min = 0)
    {
        $current_date = date('Y-m-d');
        $three_months_ago = date('Y-m-d H:i:s', strtotime('-7 days', strtotime($current_date)));
        // if ($min == 53) {
        if (date('H') % 4 == 0) {
        // if ($min) {
            $dys = Db::name('dymanic')->where(['shenhe'=>1,'private'=>0])->whereTime('addtime', '>', $three_months_ago)->field('dy_id,visit,lover,comments,xuni_thumbsup,thumbsup,shares,liveness,addtime')->page($min + 1)->limit(1000)->select();
            $h = date('H');
            foreach ($dys as &$value) {
                $value['visit'] = $value['visit'] + $this->addDyDataRule($value['addtime'], 'visit');
                if (intval($h)) {
                    $value['lover'] = $value['lover'] + $this->addDyDataRule($value['addtime'], 'lover');
                    $value['xuni_thumbsup'] = $value['xuni_thumbsup'] + $this->addDyDataRule($value['addtime'], 'thumbsup');
                }
                $value['liveness'] = _calculateHotScoreNew($value['visit'], $value['comments'], $value['thumbsup']+$value['xuni_thumbsup'], $value['shares'], $value['addtime']);
                unset($value['comments'], $value['thumbsup'], $value['shares']);
            }
            (new Dymanic)->saveAll($dys);
        }
        // 系统评论
        if ($min % 5 == 0) {
            // return;
            $datetime = strtotime('-7 days');
            $dys = Db::name('dymanic')
                    ->alias('dy')
                    ->join('user u','u.id=dy.userid')
                    ->where(['dy.shenhe'=>1,'dy.source_type'=>0,'dy.private'=>0,'dy.datetime'=>['<',date('Y-m-d') . ' 00:00:00'], 'dy.addtime'=>['between',[date('Y-m-d H:i:s', $datetime), date('Y-m-d') . ' 00:00:00']], 'u.delete_time'=>0,'u.is_banned'=>0,'u.reg'=>1])
                    ->limit(10)
                    ->field('dy.dy_id,dy.comments,dy.lover,dy.thumbsup,dy.visit,dy.shares,dy.liveness,dy.addtime,u.id,u.sex,u.entertainment')
                    // ->fetchSql(true)
                    ->select();
            // var_dump($dys);exit;
            foreach ($dys as $key => $value) {
                $contents = Db::name('dycomment_template')->where(['sex'=>['in',$value['sex']=='男'?[0,2]:[0,1]]])->limit(rand(1,5))->order('last_time asc')->column('content');

                $sexWhere = [$value['sex']=='男'?'u.sex="女" and u.quality!=1':'u.sex="男" and (d.topup < 5000 or d.id is null)','(u.sex="男" and (d.topup < 5000 or d.id is null)) or (u.sex="女" and u.quality!=1)',$value['sex']=='男'?'u.sex="女" and u.quality!=1':'u.sex="男" and (d.topup < 5000 or d.id is null)'];
                $uids = Db::name('user')->alias('u')->join('user_data d','u.id=d.user_id', 'left')->where('u.is_banned=0 and u.reg=1 and u.role=0 and u.delete_time=0 and last_login_datetime < "'.date('Y-m-d H:i:s', $datetime).'" and last_login_time < "'.$datetime.'" and u.id <> '.$value['id'])->where($sexWhere[$value['entertainment']])->limit(sizeof($contents))->order(Db::raw('rand()'))->column('u.id');
                $dycomments = [];
                foreach ($contents as $k => $v) {
                    $dycomments[] = [
                        'dy_id'=>$value['dy_id'],
                        'content'=>$v,
                        'userid'=>$uids[$k],
                        'shenhe'=>1,
                        'from'=>3,
                        'addtime'=>date('Y-m-d H:i:s', time() - rand(3600, 7200))
                    ];
                }
                if (sizeof($dycomments)) {
                    Db::name('dycomment')->insertAll($dycomments);
                    Db::name('dymanic')->where(['dy_id'=>$value['dy_id']])->update([
                        'comments'=>Db::raw('comments+'.sizeof($dycomments)),
                        'liveness'=> _calculateHotScoreNew($value['visit'], $value['comments'] + sizeof($dycomments), $value['lover'], $value['shares'], $value['addtime']),
                        'datetime'=>datetime()
                    ]);
                }
            }
        }
    }

    private function addDyDataRule($time, $option){
        $timenow = time();

        $timeWeightIndex = [1, 3, 5, 7];
        $timeWeight = 0;
        switch ($option) {
            case 'lover':
                $timeWeightValue = [rand(2,3),rand(1,3),rand(1,3),rand(1,2)];
                break;
            case 'thumbsup':
                $timeWeightValue = [rand(15,20),rand(10,20),rand(10,15),rand(5,10)];
                break;
            case 'visit':
                $timeWeightValue = [rand(15,20),rand(10,20),rand(10,15),rand(5,10)];
                break;
            
            default:
                break;
        }
        for ($i=sizeof($timeWeightIndex) - 1; $i >= 0; $i--) {
            if ($timeWeightIndex[$i] <= ceil(($timenow - strtotime($time)) / 86400)) {
                $timeWeight = $timeWeightValue[$i];
                break;
            }
        }
        return $timeWeight;
    }




    public function bannedFor230918($min = 0)
    {
        // return false;
        if ($min != 10 && $min != 40) return false;
        $h = date('H');
        $day = 7;
        // if ($h >= 18) {
        //     $day = 3;
        // } else if ($h >= 8) {
        //     if ($min != 10) return false;
        //     $day = 5;
        // }
        $notin = Db::name('warn_user_records')->column('user_id');
        $users = Db::name('user')
                    ->where(['reg'=>1, 'sex' => '女','id'=>['not in', $notin],'remote'=>0])
                    ->whereTime('register_datetime','-'.$day.' days')
                    ->order('id desc')
                    ->column('id,sex,is_banned,realname_auth','id');
        $banneds = [];
        $timenow = time();
        $repeats = Db::name('user_repeat_check')->where(['user_id'=>['in',array_keys($users)]])->column('*','user_id');
        $userConfigPrices = Db::name('config_personal')->where(['user_id'=>['in',array_keys($users)]])->column('chat_price,voice_price,video_price','user_id');
        // $userData = Db::name('user_data')->where(['user_id'=>['in',array_keys($users)]])->column('topup','user_id');
        foreach ($users as $key => $value) {
            // if ($value['sex'] == '男') {
            //     if (isset($userData[$key])) {
            //         if ($userData[$key] > 0) continue;
            //     }
            // }
            // 获取记录数据
            if ($value['realname_auth'] == 2) {
                continue;
            }
            $repeat = $repeats[$key] ?? false;
            if ($repeat) {
                // $device_ids = explode(',',$repeat['device_ids']);
                // if (sizeof($device_ids) >= 2) {
                    if (!isset($userConfigPrices[$key]) || $userConfigPrices[$key]['chat_price'] == 0 && $userConfigPrices[$key]['voice_price'] == 0 && $userConfigPrices[$key]['video_price'] == 0) {
                        $ips = explode(',',$repeat['ips']);
                        $provinces = [];
                        $citys = [];
                        foreach ($ips as $v) {
                            $ipinfo = \app\utils\IpInfoUtils::infoold($v);
                            if ($v && $ipinfo) {
                                if (isset($ipinfo['province'])) {
                                    $provinces[] = $ipinfo['province'] ? $ipinfo['province'] : '';
                                }
                                if (isset($ipinfo['city'])) {
                                    $citys[] = $ipinfo['city'] ? $ipinfo['city'] : '';
                                }
                            }
                            $provinces = array_unique($provinces);
                            $citys = array_unique($citys);
                            // if (sizeof($provinces) >= 2) {
                                // if ((in_array('云南省', $provinces) || in_array('临沧市', $citys))) {
                                if (in_array('临沧市', $citys)) {
                                    $banneds[] = ['user_id'=>$key,'function'=>'api/timing/bannedFor230918','time'=>$timenow];
                                    continue 2;
                                }
                            // }
                        }
                    }
                // }
            }
        }
        if (sizeof($banneds)) {
            Db::name('warn_user_records')->insertAll($banneds);
            foreach ($banneds as $key => $value) {
                if ($users[$value['user_id']]['is_banned'] == 0) {
                    $banned_end_time = date('Y-m-d H:i:s', strtotime('+3 years'));
                    Db::name('user')->where(['id'=>$value['user_id']])->update(['is_banned'=>1,'banned_end_time'=>$banned_end_time,'banned_desc'=>'账号异常']);
                    Db::name('config_personal')->where(['user_id'=>$value['user_id']])->update(['is_read_rule'=>0]);

                    Db::name('admin_logs')->insert([
                        'channel' => 3,
                        'toward' => 0,
                        'money' => 0,
                        'user_id' => $value['user_id'],
                        'content' => 'IP风控,封禁账号至' . $banned_end_time
                    ]);
                    // Privatechat::notice($value['user_id'], '封禁账号至' . $banned_end_time . ' 原因：账号异常', json_encode(['type'=>1, 'content'=>'申请解除封号','state'=>0], JSON_UNESCAPED_UNICODE), 1, -3);
                }
            }
        }
    }


    public function bannedFor230927($min='')
    {
        if ($min != 15 && $min != 35 && $min != 55) return false;

        $warn_user_records = Db::name('warn_user_records')->column('user_id');
        $warn_user_ids = Db::name('warn_user_records')->alias('a')->join('user b', 'a.user_id=b.id')->where(['b.is_banned'=>1])->column('a.user_id');
        $user_repeat_checks = Db::name('user_repeat_check')->where(['user_id'=>['in',$warn_user_ids]])->field('device_ids,pay_ids')->select();
        $device_ids = array_column($user_repeat_checks, 'device_ids');
        $device_ids = implode(',',$device_ids);
        $device_ids = explode(',',$device_ids);
        $device_ids = array_unique(array_filter($device_ids));
        $user_ids = [];
        foreach ($device_ids as $key => $value) {
            $users = Db::name('user_repeat_check')
                            ->where(['user_id'=>['not in', $warn_user_ids]])
                            ->where('find_in_set("'.$value.'",device_ids)')
                            ->cache(600)
                            ->column('user_id');
            $user_ids = array_merge($user_ids, $users);
        }
        $pay_ids = array_column($user_repeat_checks, 'pay_ids');
        $pay_ids = implode(',',$pay_ids);
        $pay_ids = explode(',',$pay_ids);
        $pay_ids = array_unique(array_filter($pay_ids));
        foreach ($pay_ids as $key => $value) {
            $users = Db::name('user_repeat_check')
                            ->where(['user_id'=>['not in', $warn_user_ids]])
                            ->where('find_in_set("'.$value.'",pay_ids)')
                            ->column('user_id');
            $user_ids = array_merge($user_ids, $users);
        }
        $user_ids = array_unique($user_ids);
        if (sizeof($user_ids)) {
            $users = Db::name('user')
                        ->where(['reg'=>1,'id'=>['in', $user_ids]])
                        ->column('id,sex,is_banned,realname_auth','id');
            $banneds = [];
            $timenow = time();
            foreach ($users as $key => $value) {
                if (in_array($key, $warn_user_records)) continue;
                $banneds[] = ['user_id'=>$key,'function'=>'api/timing/bannedFor230927','time'=>$timenow];

                if ($value['is_banned'] == 0) {
                    // $banned_end_time = date('Y-m-d H:i:s', strtotime('+3 years'));
                    // Db::name('user')->where(['id'=>$key])->update(['is_banned'=>1,'banned_end_time'=>$banned_end_time,'banned_desc'=>'账号异常']);
                    // Db::name('config_personal')->where(['user_id'=>$key])->update(['is_read_rule'=>0]);
                    // Privatechat::notice($key, '封禁账号至' . $banned_end_time . ' 原因：账号异常', json_encode(['type'=>1, 'content'=>'申请解除封号','state'=>0], JSON_UNESCAPED_UNICODE), 1, -3);
                }
            }
            $totalCount = sizeof($banneds);
            if ($totalCount) {
                if ($totalCount > 60) {
                    $batchSize = 40;
                    $batchCount = ceil($totalCount / $batchSize);

                    for ($i = 0; $i < $batchCount; $i++) {
                        $startIndex = $i * $batchSize;
                        $endIndex = min(($i + 1) * $batchSize, $totalCount);
                        $batchData = array_slice($banneds, $startIndex, $endIndex - $startIndex);
                        Db::name('warn_user_records')->insertAll($batchData);
                    }
                } else {
                    Db::name('warn_user_records')->insertAll($banneds);
                }
            }
        }
    }


    public function bannedFor20240522($min = 0)
    {
        // return false;
        if ($min != 10 && $min != 30 && $min != 50) return false;
        $h = date('H');
        $day = 7;
        $notin = Db::name('warn_user_records')->column('user_id');
        $users = Db::name('user')
                    ->where(['reg'=>1, 'sex' => '女','id'=>['not in', $notin],'remote'=>0])
                    ->whereTime('register_datetime','-'.$day.' days')
                    ->order('id desc')
                    ->column('id,sex,is_banned,realname_auth','id');
        $userCerts = Db::name('user_certification')->where(['types'=>1, 'user_id'=>['in', array_keys($users)]])->column('status','user_id');
        $banneds = [];
        $timenow = time();
        $repeats = Db::name('user_repeat_check')->where(['user_id'=>['in',array_keys($users)]])->column('*','user_id');
        $userConfigPrices = Db::name('config_personal')->where(['user_id'=>['in',array_keys($users)]])->column('chat_price,voice_price,video_price','user_id');
        $chats = Db::name('privatechat')->where(['userid'=>['in', array_keys($users)], 'single'=>['in', [0,2]], 'is_fate'=>0, 'front_id'=>['<>', '']])->group('userid')->field('count(*) count, userid')->select();
        $chatsData = [];
        foreach ($chats as $key => $value) {
            $chatsData[$value['userid']] = $value['count'];
        }
        foreach ($users as $key => $value) {
            if (!isset($userCerts[$key]) || $userCerts[$key] < 0 || $value['realname_auth'] == 0) {
                continue;
            }
            $repeat = $repeats[$key] ?? false;
            if ($repeat) {
                $device_ids = explode(',',$repeat['device_ids']);
                if (sizeof($device_ids) >= 2) {
                    if (!isset($userConfigPrices[$key]) || $userConfigPrices[$key]['chat_price'] == 0 && $userConfigPrices[$key]['voice_price'] == 0 && $userConfigPrices[$key]['video_price'] == 0) {
                        if (isset($chatsData[$key]) && $chatsData[$key] > 5) {
                            $banneds[] = ['user_id'=>$key,'function'=>'api/timing/bannedFor20240522','time'=>$timenow];
                        }
                    }
                }
            }
        }
        if (sizeof($banneds)) {
            Db::name('warn_user_records')->insertAll($banneds);
            foreach ($banneds as $key => $value) {
                if ($users[$value['user_id']]['is_banned'] == 0) {
                    $banned_end_time = date('Y-m-d H:i:s', strtotime('+3 years'));
                    Db::name('user')->where(['id'=>$value['user_id']])->update(['is_banned'=>1,'banned_end_time'=>$banned_end_time,'banned_desc'=>'账号异常']);
                    Db::name('config_personal')->where(['user_id'=>$value['user_id']])->update(['is_read_rule'=>0]);

                    Db::name('admin_logs')->insert([
                        'channel' => 3,
                        'toward' => 0,
                        'money' => 0,
                        'user_id' => $value['user_id'],
                        'content' => 'IP风控,封禁账号至' . $banned_end_time
                    ]);
                    // Privatechat::notice($value['user_id'], '封禁账号至' . $banned_end_time . ' 原因：账号异常', json_encode(['type'=>1, 'content'=>'申请解除封号','state'=>0], JSON_UNESCAPED_UNICODE), 1, -3);
                }
            }
        }
    }


    public function setOnlineAll()
    {
        Db::name('user')->where(['is_online'=>1, 'last_login_time'=>['<', strtotime('-3 days')]])->update(['is_online'=>0]);
    }

    // 独占周四凌晨3点18分
    public function clearUnreplySystemHiChat($min='')
    {
        // if ($min != 10) return '';
        // $h = date('H');
        // if ($h != 0) return '';


        if ($min != 18) return '';
        $w = date('w');
        if ($w != 3) return '';
        $h = date('H');
        if ($h != 3) return '';

        $config = Db::name('config_system')->where(['category' => 'kefu'])->column('title, content');
        $kefu = intval($config['id']);

        $data = Db::name('privatechat')->where(['type'=>0,'userid'=>['<>',$kefu], 'is_public'=>0, 'front_id'=>'', 'content'=>['<>','我在这儿呢']])->select();

        $lastid = Db::name('privatechat')->order('id desc')->value('id');
        foreach ($data as $key => $value) {
            $hasReply = Db::name('privatechat')->where(['userid'=>$value['touserid'], 'touserid'=>$value['userid'], 'single'=>0])->find();
            if ($hasReply) {
                continue;
            }

            $this->clearBothChat($value['userid'], $value['touserid'], $lastid);
        }
        return;

    }
    // 独占周四凌晨3点46分
    public function clearUnreplySystemHiChat2($min='')
    {
        if ($min != 46) return '';
        $w = date('w');
        if ($w != 3) return '';
        $h = date('H');
        if ($h != 3) return '';
        $zhaohus = Db::name('privatechat_zhaohu')->where(['types'=>2])->column('content');
        $lastid = Db::name('privatechat')->order('id desc')->value('id');
        foreach ($zhaohus as $key => $value) {
            $chatLists = Db::name('chat_lists')
                            ->where([
                                'user_content|another_content'=>$value,
                                'user_first'=>0,
                                'another_first'=>0,
                                'user_time|another_time'=>['between', [1, strtotime('-7 days')]]
                            ])->field('user_id,another_id')
                            // ->fetchSql(true)
                            ->select();
                            // var_dump($chatLists);exit;
            foreach ($chatLists as $k => $v) {
                $this->clearBothChat($v['user_id'], $v['another_id'], $lastid);
            }
        }
        return;
    }

    // 独占周三凌晨3点16分
    public function clearUnreplySayHiChat($min='')
    {
        if ($min != 16) return '';
        $w = date('w');
        if ($w != 2) return '';
        $h = date('H');
        if ($h != 3) return '';

        $data = Db::name('chat_lists')->where('user_first=1 or another_first=1')->select();
        $lastid = Db::name('privatechat')->order('id desc')->value('id');
        foreach ($data as $key => $value) {
            $this->clearBothChat($value['user_id'], $value['another_id'], $lastid);
        }
        return;
    }

    private function clearBothChat($userid, $touserid, $lastid)
    {
        $last = Db::query("(select * from privatechat where userid=".$userid." and touserid=".$touserid.") union (select * from privatechat where userid=".$touserid." and touserid=".$userid.") order by id desc");

        $ids = array_column($last, 'id');
        $idstrs = implode(',', $ids);
        if ($idstrs) {
            Db::name('privatechat')->where(['id'=>['in', $idstrs]])->update(['status'=>4]);
            // Db::query("delete from privatechat where id in ($idstrs)");
        }

        $last_id = $last[0]['id'] ?? $lastid;
        $db = Db::name('privatechat_dele_task')->insertAll([
            ['userid'=>$userid, 'touserid'=>$touserid, 'last_id'=>$last_id,  'create_time'=>time()],
            ['userid'=>$touserid, 'touserid'=>$userid, 'last_id'=>$last_id,  'create_time'=>time()]
        ]);

        $where = $userid > $touserid ? ['user_id'=>$touserid, 'another_id'=>$userid] : ['user_id'=>$userid, 'another_id'=>$touserid];
        Db::name('chat_lists')->where($where)->delete();
        Db::name('chat_charge_records')->where($where)->delete();
    }


    public function getuserdata($date)
    {
        $user_repeat_checks = Db::name('user_repeat_check')->field('user_id,device_brand,os,last_login_app_version')->select();
        $all = array_column($user_repeat_checks, 'user_id');
        $allusers = Db::name('user')->where(['reg'=>1, 'delete_time'=>0])->field('id,age,sex')->select();
        $all1 = array_column($allusers, 'id');
        $all = array_intersect($all, $all1);
        $data['age_areas'] = [
            'female'=>[
                'lt_18'=>0,
                'bt_18_23'=>0,
                'bt_24_30'=>0,
                'bt_31_40'=>0,
                'bt_41_50'=>0,
                'bt_51_59'=>0,
                'gte_60'=>0,
            ],
            'male'=>[
                'lt_18'=>0,
                'bt_18_23'=>0,
                'bt_24_30'=>0,
                'bt_31_40'=>0,
                'bt_41_50'=>0,
                'bt_51_59'=>0,
                'gte_60'=>0,
            ]
        ];
        foreach ($allusers as $key => $value) {
            $sex = $value['sex'] == '男' ? 'male' : 'female';
                if( $value['age']<18) {
                    $data['age_areas'][$sex]['lt_18']++;
                } else if( $value['age']>=18&&$value['age']<=23) {
                    $data['age_areas'][$sex]['bt_18_23']++;
                } else if( $value['age']>=24&&$value['age']<=30) {
                    $data['age_areas'][$sex]['bt_24_30']++;
                } else if( $value['age']>=31&&$value['age']<=40) {
                    $data['age_areas'][$sex]['bt_31_40']++;
                } else if( $value['age']>=41&&$value['age']<=50) {
                    $data['age_areas'][$sex]['bt_41_50']++;
                } else if( $value['age']>=51&&$value['age']<=59) {
                    $data['age_areas'][$sex]['bt_51_59']++;
                } else if( $value['age']>=60) {
                    $data['age_areas'][$sex]['gte_60']++;
                }
        }

        $device_brands = ['iphone','huawei','xiaomi','oppo','vivo','honor','samsung','meizu','oneplus'];
        $device_brands_count = 0;
        $data['device_brands'] = [];

        $system_versions = ['Android 4','Android 5','Android 6','Android 7','Android 8','Android 9','Android 10','Android 11','Android 12','Android 13','Android 14','Android 15','Android 16','Android 17', 'iPhone OS 10', 'iPhone OS 11', 'iPhone OS 12', 'iPhone OS 13', 'iPhone OS 14', 'iPhone OS 15', 'iPhone OS 16', 'iPhone OS 17', 'iPhone OS 18', 'iPhone OS 19', 'iPhone OS 20'];
        $system_versions_count = 0;
        $data['system_versions'] = [];

        $app_versions = Db::name('user_repeat_check')->where(['last_login_app_version'=>['>',0]])->group('last_login_app_version')->column('last_login_app_version');
        $app_versions_count = 0;
        $data['app_versions'] = [];

        foreach ($user_repeat_checks as $key => $value) {
            if (!in_array($value['user_id'], $all)) continue;
            foreach ($device_brands as $k => $v) {
                if (stripos($value['device_brand'], $v) === false) continue;
                if(!isset($data['device_brands'][$v])) {
                    $data['device_brands'][$v] = 0;
                }
                $data['device_brands'][$v]++;
                $device_brands_count++;
            }
            foreach ($system_versions as $k => $v) {
                if (stripos($value['os'], $v) === false) continue;
                if(!isset($data['system_versions'][$v])) {
                    $data['system_versions'][$v] = 0;
                }
                $data['system_versions'][$v]++;
                $system_versions_count++;
            }
            foreach ($app_versions as $k => $v) {
                if ($v != $value['last_login_app_version']) continue;
                if(!isset($data['app_versions'][' '.$v])) {
                    $data['app_versions'][' '.$v] = 0;
                }
                $data['app_versions'][' '.$v]++;
                $app_versions_count++;
            }
        }
        array_multisort($data['device_brands'], SORT_DESC);
        array_multisort($data['system_versions'], SORT_DESC);
        array_multisort($data['app_versions'], SORT_DESC);
        $data['device_brands']['other'] = sizeof($all) - $device_brands_count;
        $data['system_versions']['other'] = sizeof($all) - $system_versions_count;
        $data['app_versions']['other'] = sizeof($all) - $app_versions_count;



        $date = $date ? $date : date('Y-m-d');
        $start = $date . ' 00:00:00';
        $end = $date . ' 23:59:59';

        $start_id = _day_first_id($start);
        $end_id = _day_first_id(date('Y-m-d', strtotime($end)+86400), $start_id);

        $chats = Db::name('privatechat')->where(['id'=>['between', [$start_id, $end_id-1]]])->field('id,userid,touserid,type,data,money,score,finish,addtime,second')->select();
        
        $time_2 = strtotime($date . ' 02:00:00');
        $time_4 = strtotime($date . ' 04:00:00');
        $time_6 = strtotime($date . ' 06:00:00');
        $time_8 = strtotime($date . ' 08:00:00');
        $time_10 = strtotime($date . ' 10:00:00');
        $time_12 = strtotime($date . ' 12:00:00');
        $time_14 = strtotime($date . ' 14:00:00');
        $time_16 = strtotime($date . ' 16:00:00');
        $time_18 = strtotime($date . ' 18:00:00');
        $time_20 = strtotime($date . ' 20:00:00');
        $time_22 = strtotime($date . ' 22:00:00');
        $time_24 = strtotime($date . ' 23:59:59');
        $keys = ['0'=>'word', '9'=>'audio', '10'=>'video'];
        $data['chat'] = [
            '0_2'=>['word'=>0,'audio'=>0,'video'=>0,'ahs'=>0,'vhs'=>0,'ae'=>0,'ve'=>0,'at'=>0,'vt'=>0,'aeid'=>[],'veid'=>[]],
            '2_4'=>['word'=>0,'audio'=>0,'video'=>0,'ahs'=>0,'vhs'=>0,'ae'=>0,'ve'=>0,'at'=>0,'vt'=>0,'aeid'=>[],'veid'=>[]],
            '4_6'=>['word'=>0,'audio'=>0,'video'=>0,'ahs'=>0,'vhs'=>0,'ae'=>0,'ve'=>0,'at'=>0,'vt'=>0,'aeid'=>[],'veid'=>[]],
            '6_8'=>['word'=>0,'audio'=>0,'video'=>0,'ahs'=>0,'vhs'=>0,'ae'=>0,'ve'=>0,'at'=>0,'vt'=>0,'aeid'=>[],'veid'=>[]],
            '8_10'=>['word'=>0,'audio'=>0,'video'=>0,'ahs'=>0,'vhs'=>0,'ae'=>0,'ve'=>0,'at'=>0,'vt'=>0,'aeid'=>[],'veid'=>[]],
            '10_12'=>['word'=>0,'audio'=>0,'video'=>0,'ahs'=>0,'vhs'=>0,'ae'=>0,'ve'=>0,'at'=>0,'vt'=>0,'aeid'=>[],'veid'=>[]],
            '12_14'=>['word'=>0,'audio'=>0,'video'=>0,'ahs'=>0,'vhs'=>0,'ae'=>0,'ve'=>0,'at'=>0,'vt'=>0,'aeid'=>[],'veid'=>[]],
            '14_16'=>['word'=>0,'audio'=>0,'video'=>0,'ahs'=>0,'vhs'=>0,'ae'=>0,'ve'=>0,'at'=>0,'vt'=>0,'aeid'=>[],'veid'=>[]],
            '16_18'=>['word'=>0,'audio'=>0,'video'=>0,'ahs'=>0,'vhs'=>0,'ae'=>0,'ve'=>0,'at'=>0,'vt'=>0,'aeid'=>[],'veid'=>[]],
            '18_20'=>['word'=>0,'audio'=>0,'video'=>0,'ahs'=>0,'vhs'=>0,'ae'=>0,'ve'=>0,'at'=>0,'vt'=>0,'aeid'=>[],'veid'=>[]],
            '20_22'=>['word'=>0,'audio'=>0,'video'=>0,'ahs'=>0,'vhs'=>0,'ae'=>0,'ve'=>0,'at'=>0,'vt'=>0,'aeid'=>[],'veid'=>[]],
            '22_24'=>['word'=>0,'audio'=>0,'video'=>0,'ahs'=>0,'vhs'=>0,'ae'=>0,'ve'=>0,'at'=>0,'vt'=>0,'aeid'=>[],'veid'=>[]]
            ];
        $chatuids = [];
        $twokey = [9=>'a',10=>'v'];
        $xiaoFeis = [];
        $shouRus = [];
        foreach ($chats as $value) {
            $chatuids[] = $value['userid'];
            if (!isset($keys[$value['type']])) {
                continue;
            }
            $time = strtotime($value['addtime']);
            $timekey = '';
            if ($time < $time_2) {
                    $timekey = '0_2';
                } else if ($time >= $time_2 && $time < $time_4) {
                    $timekey = '2_4';
                } else if ($time >= $time_4 && $time < $time_6) {
                    $timekey = '4_6';
                } else if ($time >= $time_6 && $time < $time_8) {
                    $timekey = '6_8';
                } else if ($time >= $time_8 && $time < $time_10) {
                    $timekey = '8_10';
                } else if ($time >= $time_10 && $time < $time_12) {
                    $timekey = '10_12';
                } else if ($time >= $time_12 && $time < $time_14) {
                    $timekey = '12_14';
                } else if ($time >= $time_14 && $time < $time_16) {
                    $timekey = '14_16';
                } else if ($time >= $time_16 && $time < $time_18) {
                    $timekey = '16_18';
                } else if ($time >= $time_18 && $time < $time_20) {
                    $timekey = '18_20';
                } else if ($time >= $time_20 && $time < $time_22) {
                    $timekey = '20_22';
                } else if ($time >= $time_22 && $time <= $time_24) {
                    $timekey = '22_24';
            }
            if ($value['type'] == 10) {
                $json_data = json_decode($value['data'], true);
                if ($json_data && isset($json_data['status']) && $json_data['status'] == 1) {
                    $data['chat'][$timekey][$keys[$value['type']]]++;
                }
            } else {
                $data['chat'][$timekey][$keys[$value['type']]]++;
            }

            if (in_array($value['type'], [9,10])) {
                if ($value['money']>0) {
                    $data['chat'][$timekey][$twokey[$value['type']].'hs']++;
                    $data['chat'][$timekey][$twokey[$value['type']].'t']+=$value['second'];
                }
                if (strpos($value['data'], 'hpr') !== false) {
                    $data['chat'][$timekey][$twokey[$value['type']].'e']++;
                    $data['chat'][$timekey][$twokey[$value['type']].'eid'][] = $value['id'];
                }
            }


            if ($value['money']>0) {
                $xiaoFeis[] = $value['userid'];
            }
            if ($value['score']>0 && $value['finish']) {
                $shouRus[] = $value['touserid'];
            }
        }
        $xiaoFeis = array_unique($xiaoFeis);
        $shouRus = array_unique($shouRus);
        foreach ($data['chat'] as &$value) {
            $value['aeid'] = implode(',',$value['aeid']);
            $value['veid'] = implode(',',$value['veid']);
        }
        $data['chat']['usersexcount']['male'] = Db::name('user')->where(['id'=>['in',$chatuids], 'sex'=>'男'])->count();
        $data['chat']['usersexcount']['female'] = sizeof($chatuids) - $data['chat']['usersexcount']['male'];
        $data['chat']['usersexcount']['female_s'] = sizeof($xiaoFeis);
        $data['chat']['usersexcount']['male_s'] = sizeof($shouRus);
        $data['chat']['count'] = sizeof($chats);

        $sql = 'SELECT COUNT(*) AS count_result FROM chat_lists WHERE (user_id IN (SELECT id FROM user WHERE reg = 1 AND sex = "女" AND delete_time = 0 AND id != 5559516) AND user_first = 0 AND another_id != 5559516) OR (another_id IN (SELECT id FROM user WHERE reg = 1 AND sex = "女" AND delete_time = 0 AND id != 5559516) AND another_first = 0 AND user_id != 5559516);';
        $chatlistsCount = Db::query($sql);
        $data['chat']['chat_list_count_en'] = $chatlistsCount[0]['count_result'];

        $topups = Db::name('topup')->whereTime('addtime', 'yesterday')->where(['state'=>1])->group('fk_userid')->column('sum(price) count_price, sum(money) count_money','fk_userid');
        $data['topup']['count_price'] = array_sum(array_column(array_values($topups), 'count_price'));
        $data['topup']['count_money'] = array_sum(array_column(array_values($topups), 'count_money'));
        $data['topup']['count_account'] = sizeof($topups);
        $fk_userids = array_keys($topups);
        $data['topup']['count_limit'] = 0;
        $data['topup']['limit_uids'] = [];

        $config = Config::index('topup');
        $userlimits = Db::name('topup_limit')->where(['user_id'=>['in', $fk_userids], 'value'=>['>', 0]])->column('value', 'user_id');
        $userDatas = Db::name('user_data')->where(['user_id'=>['in', $fk_userids]])->column('topup','user_id');
        foreach ($fk_userids as $topupuid) {
            if ($topups[$topupuid]['count_price'] >= $config['topup_max']) {
                $data['topup']['count_limit']++;
                $data['topup']['limit_uids'][] = $topupuid;
                continue;
            }
            $topupCount = $userDatas[$topupuid] ?? 0;
            if($topupCount >= 15000 && $topups[$topupuid]['count_price'] > 20){
                $data['topup']['count_limit']++;
                $data['topup']['limit_uids'][] = $topupuid;
                continue;
            }
            if($topupCount >= 10000 && $topups[$topupuid]['count_price'] > 30){
                $data['topup']['count_limit']++;
                $data['topup']['limit_uids'][] = $topupuid;
                continue;
            }
            if($topupCount >= 7000 && $topups[$topupuid]['count_price'] > 50){
                $data['topup']['count_limit']++;
                $data['topup']['limit_uids'][] = $topupuid;
                continue;
            }
            if($topupCount >= 3000 && $topups[$topupuid]['count_price'] > 80){
                $data['topup']['count_limit']++;
                $data['topup']['limit_uids'][] = $topupuid;
                continue;
            }
        }

        $data['topup']['limit_uids'] = implode(',', $data['topup']['limit_uids']);


        return $data;
    }
    public function tongjiUserData($date = '', $return = false)
    {
        $date = $date ? $date : date('Y-m-d', strtotime('-1 day'));
        $time = strtotime($date);

        $data = Db::name('tongji_user_data')->where(['date'=>$date])->find();

        if ($data) {
            $data['age_areas'] = json_decode($data['age_areas'], true);
            $data['device_brands'] = json_decode($data['device_brands'], true);
            $data['system_versions'] = json_decode($data['system_versions'], true);
            $data['app_versions'] = json_decode($data['app_versions'], true);
            $data['chat'] = json_decode($data['chat'], true);
        } else {
            $data = $this->getuserdata($date);
            if (strtotime($date) < strtotime(date('Y-m-d'))) {
                $insertData['date'] = $date;
                $insertData['age_areas'] = json_encode($data['age_areas']);
                $insertData['device_brands'] = json_encode($data['device_brands']);
                $insertData['system_versions'] = json_encode($data['system_versions']);
                $insertData['app_versions'] = json_encode($data['app_versions']);
                $insertData['chat'] = json_encode($data['chat']);
                $insertData['topup'] = json_encode($data['topup']);
                if ($data['chat']['count']) {
                    Db::name('tongji_user_data')->insert($insertData);
                }
            }
        }
        if ($return) {
            return $data;
        }
    }

    public function tongJIDynamic($date = '', $return = false)
    {
        $date = $date ? $date : date('Y-m-d', strtotime('-1 day'));
        $time = strtotime($date);

        $data = Db::name('tongji_dynamic')->where(['date'=>$date])->find();

        if ($data) {
            $data['times'] = json_decode($data['times'], true);
            $data['users'] = json_decode($data['users'], true);
        } else {
            $data = $this->getTongJIDynamic($date);
            $this->tongjiUnreply($date);
            if (strtotime($date) < strtotime(date('Y-m-d'))) {
                $insertData['date'] = $date;
                $insertData['txt'] = $data['txt'] ?? 0;
                $insertData['image'] = $data['image'] ?? 0;
                $insertData['video'] = $data['video'] ?? 0;
                $insertData['times'] = json_encode($data['times']);
                $insertData['users'] = json_encode($data['users']);
                Db::name('tongji_dynamic')->insert($insertData);
            }
        }
        if ($return) {
            return $data;
        }
    }

    public function getTongJIDynamic($date = '')
    {

        $date = $date ? $date : date('Y-m-d');
        $dymanic_reads = Db::name('dymanic_read')
                    ->alias('a')
                    ->join('dymanic b', 'a.dy_id=b.dy_id')
                    ->where(['shenhe'=>1,'private'=>0,'a.time'=>['between',[$date . ' 00:00:00', $date . ' 23:59:59']]])
                    ->field('a.time, a.userid, b.userid dy_userid, b.masterimg, b.video')
                    ->select();
        
        $time_2 = strtotime($date . ' 02:00:00');
        $time_4 = strtotime($date . ' 04:00:00');
        $time_6 = strtotime($date . ' 06:00:00');
        $time_8 = strtotime($date . ' 08:00:00');
        $time_10 = strtotime($date . ' 10:00:00');
        $time_12 = strtotime($date . ' 12:00:00');
        $time_14 = strtotime($date . ' 14:00:00');
        $time_16 = strtotime($date . ' 16:00:00');
        $time_18 = strtotime($date . ' 18:00:00');
        $time_20 = strtotime($date . ' 20:00:00');
        $time_22 = strtotime($date . ' 22:00:00');
        $time_24 = strtotime($date . ' 23:59:59');
        $keys = ['txt', 'image', 'video'];
        $data['txt'] = 0;
        $data['image'] = 0;
        $data['video'] = 0;
        $data['times'] = [
            '0_2'=>['txt'=>0,'image'=>0,'video'=>0],
            '2_4'=>['txt'=>0,'image'=>0,'video'=>0],
            '4_6'=>['txt'=>0,'image'=>0,'video'=>0],
            '6_8'=>['txt'=>0,'image'=>0,'video'=>0],
            '8_10'=>['txt'=>0,'image'=>0,'video'=>0],
            '10_12'=>['txt'=>0,'image'=>0,'video'=>0],
            '12_14'=>['txt'=>0,'image'=>0,'video'=>0],
            '14_16'=>['txt'=>0,'image'=>0,'video'=>0],
            '16_18'=>['txt'=>0,'image'=>0,'video'=>0],
            '18_20'=>['txt'=>0,'image'=>0,'video'=>0],
            '20_22'=>['txt'=>0,'image'=>0,'video'=>0],
            '22_24'=>['txt'=>0,'image'=>0,'video'=>0]
        ];
        $data['users'] = [];
        foreach($dymanic_reads as $value) {
            $time = strtotime($value['time']);
            $timekey = '';
            if ($time < $time_2) {
                    $timekey = '0_2';
                } else if ($time >= $time_2 && $time < $time_4) {
                    $timekey = '2_4';
                } else if ($time >= $time_4 && $time < $time_6) {
                    $timekey = '4_6';
                } else if ($time >= $time_6 && $time < $time_8) {
                    $timekey = '6_8';
                } else if ($time >= $time_8 && $time < $time_10) {
                    $timekey = '8_10';
                } else if ($time >= $time_10 && $time < $time_12) {
                    $timekey = '10_12';
                } else if ($time >= $time_12 && $time < $time_14) {
                    $timekey = '12_14';
                } else if ($time >= $time_14 && $time < $time_16) {
                    $timekey = '14_16';
                } else if ($time >= $time_16 && $time < $time_18) {
                    $timekey = '16_18';
                } else if ($time >= $time_18 && $time < $time_20) {
                    $timekey = '18_20';
                } else if ($time >= $time_20 && $time < $time_22) {
                    $timekey = '20_22';
                } else if ($time >= $time_22 && $time <= $time_24) {
                    $timekey = '22_24';
            }
            $type = 0;
            if ($value['video']) {
                $type = 2;
            } else if ($value['masterimg']) {
                $type = 1;
            }
            $data['times'][$timekey][$keys[$type]]++;
            $data[$keys[$type]]++;

            if (!isset($data['users'][$value['userid']])) {
                $data['users'][$value['userid']] = ['txt'=>0, 'image'=>0, 'video'=>0, 'count'=>0];
            }
            $data['users'][$value['userid']][$keys[$type]]++;
            $data['users'][$value['userid']]['count']++;
        }

        uasort($data['users'], function($a, $b) {
            return $b["count"] - $a["count"]; // 按"count"键的值降序排序
        });
        return $data;
    }

    public function chatBackEnBlackList()
    {
        $page_key = 'chatBackEnBlackList_page';
        $page = cache($page_key);
        $page = $page ? $page : 1;
        echo $page;

        // $data = Db::name('volley_desc')->where(['time'=>['>', 1685548800], 'content' => ['like', '%未回复消息，过期返还金币']])->page($page)->limit(100)->select();
        $data = Db::connect('database8')->name('volley_desc')->where(['time'=>['>', 1685548800], 'content' => ['like', '%未回复消息，过期返还金币']])->page($page)->limit(100)->select();

        foreach ($data as $key => $value) {
            // 使用正则表达式匹配数字
            if (preg_match('/\((\d+)\)/', $value['content'], $matches)) {
                // $matches[1] 包含匹配到的数字
                $number = $matches[1];
                // echo "提取到的数字是：$number";
            } else {
                // echo "未找到匹配的数字";
                continue;
            }

            Db::name('blacklist')->where(['user_id'=>$value['user_id'], 'to_user'=>$number])->delete();
            Db::name('blacklist')->where(['user_id'=>$number, 'to_user'=>$value['user_id']])->delete();
        }


        cache($page_key, ++$page, 86400);
        header("refresh:1;");
    }

    public function checkUnpayTopup()
    {
        $timenow = time();
        $data = Db::name('topup')
                    ->alias('a')
                    ->join('topup_unpay_receipt b', 'a.numbers=b.numbers', 'left')
                    ->field('a.*')
                    ->where([
                        'a.state'=>0,
                        'a.addtime'=>['between', [
                            date('Y-m-d H:i:s', strtotime('-1 hours')),
                            date('Y-m-d H:i:s', strtotime('-2 minute'))
                        ]]
                    ])->where('b.id is null')->order('id desc')->limit(100)->fetchSql(false)->select();

        $inserts = [];

        $config = Db::name('config_system')->where(['category' => 'kefu'])->column('title, content');
        $kefu = (int)strip_tags($config['id']);

        foreach ($data as $key => $value) {
            $result = 0;
            try {
                if ($value['type']) {
                    $result = action('api/Alipay/checkOrder', ['out_trade_no'=>$value['numbers']]);
                } else {
                    $result = action('api/Wechat2/checkOrder', ['out_trade_no'=>$value['numbers']]);
                }
            } catch (\Exception $e) {
                $result = 0;
            }
            if ($result) {
                $notifyState = 0;
                try {
                    // Privatechat::tip($value['fk_userid'], $kefu, '『系统』检测到充值未到账', '', 1, 0);
                    $notifyState = OrderCommon::notify($value['numbers'], $result);
                } catch (\Exception $e) {
                }
                if ($notifyState) {
                    $inserts[] = [
                        'numbers'   =>  $value['numbers'],
                        'type'   =>  $value['type'],
                        'state'   =>  $value['state'],
                        'pay_time'   =>  $value['type']?$result['time_end_timestamp']:$result->time_end_timestamp,
                        'create_time'   =>  $timenow,
                        'fk_userid'   =>  $value['fk_userid'],
                        'price'   =>  $value['price'],
                        'money'   =>  $value['money'],
                        'addtime'   =>  $value['addtime'],
                    ];
                }
            }
        }
        if (!empty($inserts)) {
            Db::name('topup_unpay_receipt')->insertAll($inserts);
        }
    }

    public function tongjiUnreply($date = '', $return = false)
    {
        $date = $date ? $date : date('Y-m-d', strtotime('-1 day'));
        $time = strtotime($date);

        $data = Db::name('tongji_unreply_records')->where(['date'=>$date])->find();
        if ($data) {
            if ($return) {
                return $data;
            }
            return;
        }

        $volley_descs = Db::name('volley_desc')->where(['content'=>['like', '%未回复消息，过期返还金币']])->whereTime('time', 'between', [$date . ' 00:00:00', $date . ' 23:59:59'])->field('content,time')->select();
        $uids = [];
        foreach ($volley_descs as &$v) {
            $v['uid'] = '';
            $pattern = '/\((\d+)\)[^(]*$/'; // 匹配最后一个括号内的数字
            preg_match($pattern, $v['content'], $matches);
            if (isset($matches[1])) {
                $v['uid'] = $uids[] = $matches[1];
            } else {
                continue;
            }
        }
        $banneds = [];
        $unlines = [];
        $onlines = [];
        $last30day = strtotime('-30 day');
        $users = Db::name('user')->where(['id'=>['in',$uids]])->column('is_banned,banned_end_time,last_login_datetime', 'id');
        foreach ($users as $key => $value) {
            if ($value['is_banned']) {
                $banneds[] = $key;
            }
            if (strtotime($value['last_login_datetime']) < $last30day) {
                $unlines[] = $key;
            }
        }
        foreach ($volley_descs as $key => $value) {
            if (!isset($users[$value['uid']])) continue;
            if (strtotime($users[$value['uid']]['last_login_datetime']) >= $value['time'] - 3 * 86400) {
                $onlines[] = $value['uid'];
            }
        }



        $insert = [
            'banned_count'=>sizeof($banneds),
            'unline_count'=>sizeof($unlines),
            'online_count'=>sizeof($onlines),
            'banned'=>implode(',', $banneds),
            'unline'=>implode(',', $unlines),
            'online'=>implode(',', $onlines),
            'date'=>$date
        ];

        $insert['total'] = $insert['banned_count'] + $insert['unline_count'] + $insert['online_count'];
        Db::name('tongji_unreply_records')->insert($insert);
        if ($return) {
            return $insert;
        }
    }

    public function checkWarnChat()
    {
        $data = Db::name('warn_user_chat_records')
                ->whereTime('time', '-3 minute')
                ->select();
        $uids = array_column($data, 'user_id');
        $users = Db::name('user')->where(['id'=>['in',$uids], 'reg'=>['in',[1,2]]])->column('id,is_banned,banned_end_time,sex,reg,authcode','id');
        $real_uids = [];
        foreach ($users as $key => $value) {
            if ($value['reg']==2) {
                $users[$key] = Db::name('user')->where(['id'=>$value['authcode'], 'reg'=>1])->field('id,is_banned,banned_end_time,sex,reg,authcode')->find();
                $users[$key]['privacy'] = $value['id'];
                $real_uids[] = $users[$key]['id'];
            } else {
                $real_uids[] = $value['id'];
            }
        }
        $configPrices = Db::name('config_personal')->where(['user_id'=>['in',$real_uids]])->column('chat_price,voice_price,video_price','user_id');
        $userDatas = Db::name('user_data')->where(['user_id'=>['in',$real_uids]])->column('topup','user_id');
        $timenow = time();
        foreach ($data as $key => $value) {
            if (!isset($users[$value['user_id']])) continue;
            if ($users[$value['user_id']]['is_banned']) {
                if ($users[$value['user_id']]['banned_end_time'] > $timenow) continue;
            }
            $pattern = '/(?:(?:https?|ftp):\/\/)?(?:[\w-]+\.)+[a-z]{2,}(?:\/\S*)?/i';
            $banned = false;
            if (preg_match_all($pattern, $value['content'], $matches)) {
                $banned = true;
            } else if ($users[$value['user_id']]['sex'] == '女' && $users[$value['user_id']]['reg'] == 1 && (!isset($configPrices[$users[$value['user_id']]['id']]) || $configPrices[$users[$value['user_id']]['id']]['chat_price'] == 0)) {
                $banned = true;
            } else if ($users[$value['user_id']]['sex'] == '男' && (!isset($userDatas[$users[$value['user_id']]['id']]) || $userDatas[$users[$value['user_id']]['id']] < 20)) {
                $banned = true;
            }
            if ($banned && !$users[$value['user_id']]['is_banned']) {
                $banned_end_time = date('Y-m-d H:i:s', strtotime('+3 years'));
                Db::name('user')->where(['id'=>$users[$value['user_id']]['id']])->update(['is_banned'=>1,'banned_end_time'=>$banned_end_time, 'banned_desc'=>'账号异常']);
                Db::name('config_personal')->where(['user_id'=>$users[$value['user_id']]['id']])->update(['is_read_rule'=>0]);

                Db::name('admin_logs')->insert([
                    'channel' => 3,
                    'toward' => 0,
                    'money' => 0,
                    'user_id' => $users[$value['user_id']]['id'],
                    'content' => (isset($users[$value['user_id']]['privacy']) ? '私密号('.$users[$value['user_id']]['privacy'].')' : '').$value['reason'].',封禁账号至' . $banned_end_time
                ]);
                // Privatechat::notice($users[$value['user_id']]['id'], '封禁账号至' . $banned_end_time . ' 原因：账号异常', json_encode(['type'=>1, 'content'=>'申请解除封号','state'=>0], JSON_UNESCAPED_UNICODE), 1, -3);
            }
        }
    }

    public function rmSelectUser()
    {
        $selects = Db::name('select_users')->column('user_id');
        $ids = Db::name('user')->where(['id'=>['in',$selects], 'quality'=>['<',4]])->column('id');
        if (sizeof($ids)) {
            Db::name('select_users')->where(['user_id'=>['in',$ids]])->delete();
        }
    }


    private function setRealnameAuthFail($min = 0)
    {
        if ($min % 10) {
            return false;
        }
        $id = 20196090;
        $yqm = Db::name('user')->where(['id'=>$id])->value('yqm');
        if ($yqm) {
            $nexts = Db::name('user')->where(['yqr'=>$yqm])->column('id');
            if (empty($nexts)) {
                return false;
            }
            $userDatas = Db::name('user_data')->where(['user_id'=>['in',$nexts]])->select();
            $userDataIds = [];
            foreach ($userDatas as $key => $value) {
                if ($value['topup'] > 0 || $value['income'] > 0) {
                    $userDataIds[] = $value['user_id'];
                }
            }
            
            $nextIds = array_diff($nexts, $userDataIds);
            Db::name('user')->where(['id'=>['in',$nextIds], 'realname_auth'=>['<>', 0]])->update(['realname_auth'=>0]);
        }
    }


    public function clearCosContent()
    {
        
        // Replace with your COS credentials and configuration
        $secretId = getenv('SECRET_ID');
        $secretKey = getenv('SECRET_KEY');
        $region = 'ap-guangzhou'; // 例如：ap-guangzhou
        $bucket = 'tianyu-content-moderation-1254335172';

        // Create a COS client
        $client = new Client([
            'region' => $region,
            'credentials' => [
                'secretId' => $secretId,
                'secretKey' => $secretKey,
            ],
        ]);

        // Specify the "folder" (prefix) to delete
        $prefixToDelete = 'segment-/trtc/1400619877/';

        // List objects in the specified prefix
        $objects = $client->listObjects([
            'Bucket' => $bucket,
            'Prefix' => $prefixToDelete,
        ]);
        $num = 0;
        if (!$objects || !$objects['Contents'] || empty($objects['Contents'])) return 'empty';
        // Delete each object within the specified prefix
        foreach ($objects['Contents'] as $object) {
            if ($object['Key'] == 'segment-/trtc/1400619877/') continue;
            $client->deleteObject([
                'Bucket' => $bucket,
                'Key' => $object['Key'],
            ]);
            $num++;
        }

        echo 'Folder deleted successfully' . $num;
    }

    public function tongjiAccountant($date = '')
    {
        $date = $date ?: date('Y-m-d', strtotime('-1 days'));
        $timestamp = strtotime($date);
        $topups = Db::name('topup')->where(['state'=>1])->where('addtime','between time',[$timestamp,$timestamp+86399])->select();
        $data['total_recharge_money'] = array_sum(array_column($topups, 'price'));
        $data['total_recharge_volley'] = array_sum(array_column($topups, 'money'));

        $vipOrders = Db::name('order_common')->where(['status'=>1, 'types'=>6])->where('update_time','between time',[$timestamp,$timestamp+86399])->select();
        $data['total_recharge_vip_money'] = array_sum(array_column($vipOrders, 'money'));

        $withdraws = Db::name('withdraw_merge')->where(['state'=>1])->where('update_time','between time',[$timestamp,$timestamp+86399])->select();
        $data['total_withdrawal_score'] = array_sum(array_column($withdraws, 'price'));
        $data['total_withdrawal_money'] = array_sum(array_column($withdraws, 'money'));
        $data['withdrawal_fee_score'] = array_sum(array_column($withdraws, 'shouxu'));

        $volleys = Db::name('volley_desc')->where(['types'=>1])->where('time','between time',[$timestamp,$timestamp+86399])->field('id,content,price')->select();
        $data['gift_volley'] = 0;
        foreach ($volleys as $key => $value) {
            if ($value['content'] == '充值') continue;
            if (stripos($value['content'], '未回复消息，过期返还金币') !== false) continue;
            $data['gift_volley'] += $value['price'];
        }

        $scores = Db::name('yaoqing_records')->where(['data'=>0])->where('time','between time',[$timestamp,$timestamp+86399])->field('id,content,money')->select();
        $data['recharge_profit_score'] = 0;
        $data['direct_profit_score'] = 0;
        $data['level_1_profit_score'] = 0;
        $data['level_2_profit_score'] = 0;
        $data['level_3_profit_score'] = 0;
        $data['gift_score'] = 0;
        foreach ($scores as $key => $value) {
            if (stripos($value['content'], '提现申请驳回') !== false) continue;
            if (stripos($value['content'], '提现失败返还') !== false) continue;
            if (stripos($value['content'], '充值') !== false) {
                $data['recharge_profit_score'] += $value['money'];
            } else if (stripos($value['content'], '1级') !== false) {
                $data['level_1_profit_score'] += $value['money'];
            } else if (stripos($value['content'], '2级') !== false) {
                $data['level_2_profit_score'] += $value['money'];
            } else if (stripos($value['content'], '3级') !== false) {
                $data['level_3_profit_score'] += $value['money'];
            } else if (
                stripos($value['content'], '通话收益') !== false || 
                stripos($value['content'], '赠送的礼物') !== false || 
                stripos($value['content'], '经验文章') === 0 || 
                stripos($value['content'], '回复') === 0 || 
                stripos($value['content'], '围观') === 0 || 
                $value['content'] == '服务订单完成结算'
            ) {
                $data['direct_profit_score'] += $value['money'];
            } else {
                $data['gift_score'] += $value['money'];
            }
        }

        $data['flags'] = Db::name('user_flag')->where(['paystate'=>1])->where('create_time','between time',[$timestamp,$timestamp+86399])->sum('price');
        $data['mall_order'] = Db::name('mall_order')->where(['status'=>1])->where('create_time','between time',[$timestamp,$timestamp+86399])->sum('money');
        $data['addressgood'] = Db::name('order_of_addressgood')->where(['paystate'=>1])->where('create_time','between time',[$timestamp,$timestamp+86399])->sum('price');

        $tongji_accountant = Db::name('tongji_accountant')->where('date', $date)->find();
        if ($tongji_accountant) {
            if ((time() - strtotime($date)) / 86400 < 5) {
                Db::name('tongji_accountant')->where(['id'=>$tongji_accountant['id']])->update($data);
            }
        } else {
            $data['date'] = $date;
            Db::name('tongji_accountant')->insert($data);
        }

        return $this->pass($data);
    }

    // 清理7天以前的浏览历史记录
    public function clearDyRead($min = 0)
    {
        $hour = date('H');
        if ($hour>6 || $hour<2 || $min % 5 == 0) return '';
        $ids = Db::name('dymanic_read')->where(['time' => ['<', date('Y-m-d H:i:s', strtotime('-30 days'))]])->limit(20000)->fetchSql(false)->column('id');
        Db::name('dymanic_read')->delete($ids);
    }

    public function SyncOtherDy()
    {
        $dy = Db::name('loop_dy')->where('is_push=0 and (video_path<>"" or images_path<>"")')->find();
        $ks = Db::name('loop_ks')->where(['down_path'=>['<>',''], 'is_push'=>0])->find();

        $accessKeyId = getenv('OSS_KEYID');
        $accessKeySecret = getenv('OSS_KEYSECRET');
        $endpoint = getenv('OSS_ENDPOINT');
        $bucket = getenv('OSS_BUCKET_ZAIMA');
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        } catch (OssException $e) {
            return ['err' => $e->getMessage()];
        }
        if ($dy) {
            $userid = Db::name('loop_dy_user')->where(['sec_uid'=>$dy['sec_uid']])->value('user_id');
            $insert = [
                'title' => '',
                'content'=>$dy['desc'],
                'userid'=>$userid??0,
                'source_type'=>7,
                'source_id'=>$dy['id']
            ];
            $file_head = '/disk/py/dy/'.$dy['sec_uid'].'/';
            $files = [];
            if ($dy['video_path']) {
                $value = $file_head . $dy['video_path'];
                $filepath = ROOT_PATH . $value;
                if (file_exists($filepath)) {
                    $files[] = $filepath;
                    $ossClient->uploadFile($bucket, substr($value, 1), $filepath);
                }
                $insert['video'] = $value;
            } else {
                $imgs = explode(',', $dy['images_path']);
                foreach ($imgs as &$value) {
                    $value = $file_head . $value;
                    $filepath = ROOT_PATH . $value;
                    if (file_exists($filepath)) {
                        $files[] = $filepath;
                        $ossClient->uploadFile($bucket, substr($value, 1), $filepath);
                    }
                }
                $insert['sumbImage'] = $insert['masterimg'] = implode(',',$imgs);
            }

            $dyres = Db::name('dymanic')->insert($insert);
            if ($dyres) {
                foreach ($files as $key => $value) {
                    @unlink($value);
                }
            }
        }
        if ($ks) {
            $userid = Db::name('loop_ks_user')->where(['uid'=>$dy['uid']])->value('user_id');
            $insert = [
                'title' => '',
                'content'=>$ks['desc'],
                'userid'=>$userid??0,
                'source_type'=>8,
                'source_id'=>$ks['id']
            ];
            $files = [];
            if ($dy['down_path']) {
                $value = $dy['down_path'];
                $filepath = ROOT_PATH . $value;
                if (file_exists($filepath)) {
                    $files[] = $filepath;
                    $ossClient->uploadFile($bucket, substr($value, 1), $filepath);
                }
                $insert['video'] = $value;
            }

            $ksres = Db::name('dymanic')->insert($insert);
            if ($ksres) {
                foreach ($files as $key => $value) {
                    @unlink($value);
                }
            }
        }
    }

    public function insertWishBless()
    {
        $day = date('d');
        $hour = date('H');
        $minute = date('i');
        $timenow = time();
        if (($hour > 7 && $hour <= 11) || ($hour > 13 && $hour <= 17) || ($hour > 19 && $hour <= 22)) {
            $cachekey = 'insertWishBless';
            $cache = Cache::store('redis')->get($cachekey);
            if ($cache) return '';
            if ($minute * $hour % $day != 0) return '';
            Cache::store('redis')->set($cachekey, $timenow, rand(3,5) * 60 * 60);
        } else {
            return '';
        }
        $list = Db::name('wish')->where(['state'=>1,'delete_time'=>0])->whereTime('audit_time', '-7 day')->order('id desc')->select();
        $uids = [];
        $num = 0;
        foreach ($list as $key => $value) {
            if ($value['create_time'] % $day == 0) continue;
            if (in_array($value['user_id'], $uids)) continue;
            $uids[] = $value['user_id'];

            $bless = Db::name('wish_bless')->where(['wish_id'=>$value['id']])->column('user_id');
            $user = Db::name('user')->where(['id'=>$value['user_id']])->find();
            $sex = $user['sex'] == '男' ? '女' : '男';
            $users = Db::name('user')->where(['sex'=>$sex, 'reg'=>1, 'delete_time'=>0, 'is_banned'=>0, 'remote'=>0])->orderRaw('rand()')->limit(1)->column('id');
            foreach ($users as $k => $v) {
                Db::name('wish_bless')->insert([
                    'wish_id'   =>  $value['id'],
                    'touser_id'   =>  $value['user_id'],
                    'user_id'   =>  $v,
                    'time'      => $timenow
                ]);
                Db::name('wish')->where(['id'=>$value['id']])->setInc('bless_count');
                $num++;
            }
        }
        echo $num;
    }

    public function exceptionUser($min = 0)
    {
        if ($min != 50) return false;
        $hour = date('H');
        if (!in_array($hour, [8])) return false;

        $user = Db::name('user')
                    ->where([
                        'sex'=>'女',
                        'reg'=>1,
                        // 'yqr'=>''
                    ])
                    ->where('(score >= 30 and score < 40) or (score>50 and shouyi<400)')
                    ->whereTime('last_login_datetime', '-1 days')
                    ->column('id user_id,name,city,score,shouyi,register_datetime,last_login_datetime','id');
        $filterUids = Db::name('config_personal')->where(['user_id'=>['in', array_keys($user)], 'chat_price'=>0])->column('user_id');
        $chats = Db::name('privatechat')
            ->where(['userid'=>['in', array_keys($user)], 'single'=>0, 'is_fate'=>0, 'front_id'=>['<>', '']])
            ->whereTime('addtime', '-24 hours')
            ->field('count(*) count, userid')
            ->group('userid')
            ->select();
        $users = [];
        $uids = [];
        foreach ($chats as $key => $value) {
            if ($value['count'] > 5) {
                if ($user[$value['userid']]['score'] < 40) {
                    if (!in_array($value['userid'], $filterUids)) continue;
                }
                $users[] = $user[$value['userid']];
                $uids[] = $value['userid'];
            }
        }


        // $user = Db::name('user')
        //             ->where([
        //                 'sex'=>'女',
        //                 'reg'=>1,
        //             ])
        //             ->whereTime('last_login_datetime', '-1 days')
        //             ->column('id user_id,name,city,score,shouyi,register_datetime,last_login_datetime','id');
        // $chats = Db::name('privatechat')
        //     ->where(['userid'=>['in', array_keys($user)], 'type'=>['in', [9,10]]])
        //     ->whereTime('addtime', '-24 hours')
        //     ->field('count(*) count, userid')
        //     ->group('userid')
        //     ->select();
        // foreach ($chats as $key => $value) {
        //     if ($value['count'] > 20) {
        //         if (in_array($value['userid'], $uids)) continue;
        //         $users[] = $user[$value['userid']];
        //     }
        // }

        $withdraws = Db::name('withdraw_merge')->where(['userid'=>['in', array_column($users, 'user_id')], 'state'=>1])->group('userid')->column("sum(money)","userid");
        $timenow = time();
        foreach ($users as &$value) {
            $value['create_time'] = $timenow;
            $value['tixian'] = $withdraws[$value['user_id']] ?? 0;
        }

        if (sizeof($users)) {
            $ids = Db::name('user_exception')->column('id');
            Db::name('user_exception')->delete($ids);
            sleep(5);
            Db::name('user_exception')->insertAll(array_values($users));
        }
    }

    public function getPayids($min = 0)
    {
        $hour = date('H');
        if ($min % 8 != 0) return false;
        if (!in_array($hour, [4,5,6])) return false;

        $cachekey = 'getPayids';
        $lastid = cache($cachekey);
        $lastid = $lastid ? $lastid : 0;

        $topups = Db::name('topup')
            ->where(['state'=>1, 'data'=>['<>', ''], 'id'=>['>', $lastid]])
            ->whereTime('addtime', 'yesterday')
            ->limit(1000)
            ->select();

        foreach ($topups as $key => $value) {
            $lastid = $value['id'];
            $json = json_decode($value['data'], true);
            $payid = isset($json['openid']) ? $json['openid'] : (isset($json['buyer_id']) ? $json['buyer_id'] : '');
            if ($payid) {
                UserRepeat::InsertS($value['fk_userid'], 'pay_ids', $payid);
            }
        }
        cache($cachekey, $lastid, 1800);
    }

    public function warnUserChatRecordSendCount($min = 0)
    {
        if ($min % 2 != 0) return '';
        $data = Db::name('warn_user_chat_records')
            ->where(['content'=>['<>', ''], 'reason'=>['like', '%相同内容'], 'send_count'=>0])
            ->whereTime('time', '-5 minute')
            ->select();

        foreach ($data as $key => $value) {
            $count = Db::name('privatechat')->where(['userid'=>$value['user_id'], 'content'=>$value['content']])->whereTime('addtime','-24 hour')->count();
            Db::name('warn_user_chat_records')->where(['id'=>$value['id']])->update(['send_count'=>$count]);
        }
    }

    public function checkPrivacyAccountBind()
    {
        $fmaccounts = Db::name('user')->where(['reg'=>2])->column('device_id','authcode');
        $user_repeat_checks = Db::name('user_repeat_check')->where(['user_id'=>['in', array_keys($fmaccounts)]])->column('device_ids', 'user_id');
        $updates = [];
        foreach ($user_repeat_checks as $key => $value) {
            $device_ids = explode(',', $value);
            if (!in_array($fmaccounts[$key], $device_ids)) {
                $device_ids[] = $fmaccounts[$key];
                $device_ids = implode(',', $device_ids);

                $updates[] = ['user_id'=>$key, 'device_ids'=>$device_ids];
                // Db::name('user_repeat_check')->where(['user_id'=>$key])->update(['device_ids'=>$device_ids]);
            }
        }
        var_dump($updates);
    }

    public function yqmInit()
    {
        $users = Db::name('user')->where("reg=1 and (yqm='' or yqm is null) and delete_time=0")->limit(1000)->column('id');

        $updates = [];
        $yqms = [];
        foreach ($users as $key => $value) {
            $yqm = '';
            for ($i = 2; $i > 1; $i++) {
                $len = 5;
                $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                mt_srand(10000000 * (double)microtime());
                for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
                    $str .= $chars[mt_rand(0, $lc)];
                }
                $yqm = $str;
                if (in_array($yqm, $yqms)) {
                    continue;
                }

                $test = Db::name('user')->master()->where("yqm='$yqm' or yqr='$yqm'")->find();
                if (!$test) {
                    $yqms[] = $yqm;
                    $i = 0;
                }
            }
            $updates[] = ['id'=>$value, 'yqm'=>$yqm];
        }

        if (sizeof($updates)) {
            (new User)->saveAll($updates);
        }
        // var_dump($updates);
    }

    public function checkChatWarnWechat($min = 0)
    {
        if ($min % 5 != 0) return '';
        $uids = Db::name('chat_warn_wechat_user')->where(['status'=>1])->column('user_id');
        if (empty($uids)) return '';
        $keywords = Db::name('chat_warn_wechat_content')->where(['delete_time'=>0])->column('content');
        $whereContent = [];
        foreach ($keywords as $key => $value) {
            $whereContent[] = 'LOWER(`content`) like "%'.strtolower($value).'%"';
        }

        $chats = Db::name('privatechat')
            ->where(['userid'=>['in', $uids], 'type'=>['in', [-1, 0, 12, 20, 22]], 'single'=>['<>', 2]])
            ->where(implode(' or ', $whereContent))
            ->whereTime('addtime', '-10 minute')
            // ->fetchSql(true)
            ->select();
        // var_dump($chats);exit;
        if (empty($chats)) return '';
        $insertData = [];
        $deleTask = [];
        $timenow = time();
        foreach ($chats as $key => $value) {
            $insertData[] = [
                'user_id' => $value['userid'],
                'touser_id' => $value['touserid'],
                'content' => $value['content'],
                'send_time' => strtotime($value['addtime']),
                'check_time' => $timenow
            ];
            $deleTask[] = ['touserid'=>$value['userid'], 'userid'=>$value['touserid'], 'msg_ids'=>$value['id'], 'create_time'=>$timenow];
        }
        Db::name('privatechat')->where(['id'=>['in', array_column($chats, 'id')]])->update(['single'=>2]);

        if ($insertData) {
            Db::name('privatechat_dele_task')->insertAll($deleTask);
            Db::name('chat_warn_wechat_records')->insertAll($insertData);

            $users = Db::name('user')->where(['id'=>['in', array_column($deleTask, 'userid')]])->field('id,reg,authcode')->select();
            foreach ($users as $uk => $uv) {
                PrivatechatDeleTask::pushtask($uv['id'], $uv['reg'] == 2 ? $uv['authcode'] : $uv['id']);
            }
        }
    }


    public function lianmaiPornoStatis($min = 0)
    {
        $hour = date('H');
        if ($hour != 15 || $min != 30) return '';
        $data = Db::name('privatechat')
            ->where(['type'=>10,'data'=>['like','%触发鉴黄警报%']])
            ->whereTime('addtime', '-1 day')
            ->select();
        $users = Db::name('user')->where(['id'=>['in', array_merge(array_column($data, 'userid'), array_column($data, 'touserid'))]])->column('id,name,sex,age,shouyi,register_datetime,reg,authcode','id');
        $userDatas = Db::name('user_data')->where(['user_id'=>['in', array_keys($users)]])->column('topup', 'user_id');
        $exports = [];
        $dels = [];
        $timenow = time();
        $start = date('Y-m-d H:i:s', strtotime('-24 hours'));
        $end = date('Y-m-d H:i:s');
        $initData = Db::name('tongji_lianmai_porno')->where(['create_time' => strtotime(date('Y-m-d') . ' 15:00:00')])->column('id,num', 'user_id');
        // $old = Db::name('tongji_lianmai_porno')->column('id');
        // Db::name('tongji_lianmai_porno')->delete($old);
        foreach ($data as $key => $value) {
            $json = json_decode($value['data'], true);
            $second = isset($json['end']) ? $json['end'] - $json['start'] : 0;
            preg_match_all('/(\d+)触发鉴黄警报/', $json['hpr'], $matches);
            $pornos = $matches[1];

            foreach ($pornos as $k => $v) {
                $chatuid = $v;
                if ($users[$v]['reg'] == 1) {
                    $cachekey = 'lianmaiPornoStatis' . $v;
                    $pcount = cache($cachekey);
                    if (!$pcount) {
                        $result = Db::query("select userid from privatechat where touserid = $v and type=10 and addtime between '$start' and '$end' GROUP BY userid union (select touserid from privatechat where userid = $v and type=10 and addtime between '$start' and '$end' GROUP BY touserid)");
                        $pcount = sizeof($result);
                        cache($cachekey, $pcount, 180);
                    }
                } else {
                    $v = $users[$v]['authcode'];
                    $cachekey = 'lianmaiPornoStatis' . $v;
                    $pcount = cache($cachekey);
                    if (!$pcount) {
                        $result = Db::query("select userid from privatechat where touserid = $v and type=10 and addtime between '$start' and '$end' GROUP BY userid union (select touserid from privatechat where userid = $v and type=10 and addtime between '$start' and '$end' GROUP BY touserid)");
                        $result2 = Db::query("select userid from privatechat where touserid = $chatuid and type=10 and addtime between '$start' and '$end' GROUP BY userid union (select touserid from privatechat where userid = $chatuid and type=10 and addtime between '$start' and '$end' GROUP BY touserid)");
                        $pcount = sizeof($result) + sizeof($result2);
                        cache($cachekey, $pcount, 180);
                    }
                }
                if (isset($exports[$v])) {
                    $exports[$v]['num']++;
                    if ($second < 20) {
                        $exports[$v]['minnum']++;
                    }
                    $exports[$v]['uids'][] = $value['userid']==$chatuid?$value['touserid']:$v;
                } else {
                    $user = $users[$v] ?? ['name'=>'', 'shouyi'=>0, 'sex'=>'', 'register_datetime'=>''];
                    $exports[$v] = [
                        'user_id'=>$v,
                        'nickname'=>$user['name'],
                        'sex'=>$user['sex'],
                        'value'=>$user['sex'] == '女' ? $user['shouyi'] : ($userDatas[$v] ?? 0),
                        'register_datetime'=>$user['register_datetime'],
                        'num'=>1,
                        'uids'=>[$value['userid']==$chatuid?$value['touserid']:$v],
                        'minnum'=>$second<20?1:0,
                        'pcount'=>$pcount,
                        'create_time'=>$timenow
                    ];

                    if (isset($initData[$v])) {
                        $exports[$v]['num'] += $initData[$v]['num'];
                        $dels[] = $initData[$v]['id'];
                    }
                }
            }
        }
        foreach ($exports as &$value) {
            $value['pnum'] = sizeof(array_unique($value['uids']));
            unset($value['uids']);
        }
        if (sizeof($dels)) {
            Db::name('tongji_lianmai_porno')->delete($dels);
        }

        // echo "<pre>";
        // var_dump($exports);exit;

        Db::name('tongji_lianmai_porno')->insertAll(array_values($exports));
    }

    // 更新用户涉黄
    // 每日运行一次
    public function setUserPornoStatis($min = 0)
    {
        if ($min == 35) {
            if (date('H') != 15) return '';
        } else {
            return '';
        }
        $tongji = Db::name('tongji_lianmai_porno')->whereTime('create_time', 'month')->group('user_id')->field('sum(num) num,user_id')->select();
        $user_porno_statis = Db::name('user_porno_statis')->where(['user_id'=>['in', array_column($tongji, 'user_id')]])->column('*', 'user_id');
        $users = Db::name('user')->where(['id'=>['in', array_column($tongji, 'user_id')]])->column('porno_lv', 'id');
        $lvs = [
            '4'=>150,
            '3'=>50,
            '2'=>1,
            '1'=>0
        ];

        $insertData = [];
        $updates = [];
        $updateUsers = [];
        $timenow = time();
        foreach ($tongji as $key => $value) {
            if (!isset($users[$value['user_id']])) continue;
            $lv = 1;
            foreach ($lvs as $k => $v) {
                if ($v <= $value['num']) {
                    $lv = $k;
                    break;
                }
            }
            if (isset($user_porno_statis[$value['user_id']])) {
                if ($value['num'] != $user_porno_statis[$value['user_id']]['current']) {
                    $updates[] = [
                        'id' => $user_porno_statis[$value['user_id']]['id'],
                        'current'=>$value['num'],
                        'update_time'=>$timenow
                    ];
                    if ($user_porno_statis[$value['user_id']]['auto'] && $users[$value['user_id']] < $lv) {
                        $updateUsers[] = ['id'=>$value['user_id'], 'porno_lv'=>$lv];
                    }
                }
            } else {
                $insertData[] = [
                    'user_id'=>$value['user_id'],
                    'current'=>$value['num'],
                    'update_time'=>$timenow
                ];
                if ($users[$value['user_id']] < $lv) {
                    $updateUsers[] = ['id'=>$value['user_id'], 'porno_lv'=>$lv];
                }
            }
        }
        // echo "<pre>";
        // var_dump($insertData);exit;

        if (sizeof($insertData)) {
            Db::name('user_porno_statis')->insertAll($insertData);
        }
        if (sizeof($updates)) {
            (new UserPornoStatis)->saveAll($updates);
        }
        if (sizeof($updateUsers)) {
            (new User)->saveAll($updateUsers);
        }
    }

    // 月度更新用户涉黄统计
    // 月初运行一次
    public function setMonthUserPornoStatis($min = 0)
    {
        if ($min == 0) {
            if (!(date('d') == 1 && date('H') == 0)) return '';
        } else {
            return '';
        }
        $lvs = [
            '4'=>150,
            '3'=>50,
            '2'=>1,
            '1'=>0
        ];
        $timenow = time();
        $user_porno_statis = Db::name('user_porno_statis')->whereTime('update_time', 'last month')->select();
        $users = Db::name('user')->where(['id'=>['in', array_column($user_porno_statis, 'user_id')]])->column('porno_lv', 'id');
        $updates = [];
        $updateUsers = [];
        $dels = [];
        foreach ($user_porno_statis as $key => $value) {
            if (!isset($users[$value['user_id']])) continue;
            $userCurrentPornoLevel = $users[$value['user_id']];
            if ($userCurrentPornoLevel > 2) {
                $updateUsers[] = ['id'=>$value['user_id'], 'porno_lv'=>$userCurrentPornoLevel-1];
            } else if ($userCurrentPornoLevel == 2) {
                if ($value['current'] < $lvs['3'] && $value['before'] < $lvs['3']) {
                    $updateUsers[] = ['id'=>$value['user_id'], 'porno_lv'=>1];
                }
            }
            if ($value['current']) {
                $updates[] = [
                    'id'    =>  $value['id'],
                    'current'=>0,
                    'before' =>$value['current'],
                    'update_time'=>$timenow
                ];
            } else {
                $dels[] = $value['id'];
            }
        }

        if (sizeof($updateUsers)) {
            (new User)->saveAll($updateUsers);
        }
        if (sizeof($updates)) {
            (new UserPornoStatis)->saveAll($updates);
        }
        if (sizeof($dels)) {
            Db::name('user_porno_statis')->delete($dels);
        }
    }

    // 统计优秀用户因对方涉黄被挂断通话
    // 每5分钟运行一次
    public function tongjiPornoed()
    {
        if (date('i') % 5 != 0) return '';
        $cachekey = 'tongjiPornoed';
        $lastid = cache($cachekey) ?: 0;

        $shenhe_task_startId_cachekey = 'tongjiPornoed_shenhe_task_startId';
        $shenhe_task_startId = cache($shenhe_task_startId_cachekey) ?: 0;
        if (!$shenhe_task_startId) {
            $shenhe_task_startId = Db::name('shenhe_task')->whereTime('create_time', 'today')->value('id');
            if ($shenhe_task_startId) {
                cache($shenhe_task_startId_cachekey, $shenhe_task_startId, 3600);
            }
            $shenhe_task_startId = $shenhe_task_startId ?: 0;
        }

        $data = Db::name('shenhe_task_records')
                    ->master()
                    ->alias('r')
                    ->join('shenhe_task s', 's.task_id=r.taskid')
                    ->where(['r.id'=>['>',$lastid], 's.id'=>['>',$shenhe_task_startId], 'r.label'=>'Porn'])
                    ->whereTime('r.create_time', '-5 minute')
                    ->group('r.taskid')
                    ->field('r.id, r.userid porno_uid, r.create_time, s.order_id')
                    // ->fetchSql(true)
                    ->select();
                    // var_dump($data);exit;
        if (empty($data)) {
            return '';
        }
        $chats = Db::name('privatechat')->master()->where(['order_id'=>['in', array_column($data, 'order_id')]])->column('userid, touserid','order_id');
        if (empty($chats)) {
            return '';
        }

        $users = Db::name('user')->master()->where(['id'=>['in', array_merge(array_column(array_values($chats), 'userid'), array_column(array_values($chats), 'touserid'))], 'porno_lv'=>1])->column('id');
                    // var_dump($users);exit;

        if (empty($users)) {
            return '';
        }

        $insertData = [];
        foreach ($data as $key => $value) {
            $lastid = $value['id'];
            if (!isset($chats[$value['order_id']])) continue;
            $value = array_merge($value, $chats[$value['order_id']]);
            $touserid = $value['porno_uid'] == $value['userid'] ? $value['touserid'] : $value['userid'];
            if (in_array($touserid, $users)) {
                $insertData[] = [
                    'user_id'=>$value['porno_uid'],
                    'touser_id'=>$touserid,
                    'porno_time'=>$value['create_time']
                ];
            }
        }

        if (sizeof($insertData)) {
            Db::name('privatechat_lianmai_porno')->insertAll($insertData);
        }

        cache($cachekey, $lastid, 3600);
    }

    public function formatDyTitle($min = 1)
    {
        $hour = date('H');
        if ($hour>6 || $hour<2 || $min % 5 == 0) return '';
        $data = Db::name('dymanic')
            ->where(['source_type'=>8])
          ->where('content', 'like', '%@%')
          ->field('dy_id,content')
          ->limit(1000)
          ->select();

        $updates = [];
        foreach ($data as $row) {
            $content = preg_replace('/@[^\s]*/', '', $row['content']);
            if ($content != $row['content']) {
                $updates[] = [
                    'dy_id'=>$row['dy_id'],
                    'content'=>$content
                ];
            }
        }

        if (sizeof($updates)) {
            (new Dymanic)->saveAll($updates);
        }
    }

    public function clearDelChat()
    {
        $cachekey = 'clearDelChat';
        $lastid = cache($cachekey) ?: 0;
        $delete_user = Db::name('user')->where(['delete_time'=>['>', 0]])->cache(86400)->column('id');
        $delchats = Db::name('del_chat')->where(['id'=>['>', $lastid]])->order('id asc')->limit(20000)->select();
        $dels = [];
        foreach ($delchats as $key => $value) {
            if (sizeof($dels) > 15000) break;
            $lastid = $value['id'];
            if (in_array($value['uid'], $delete_user) || in_array($value['to_uid'], $delete_user)) {
                $dels[] = $value['id'];
            }
        }
        cache($cachekey, $lastid, 86400);
        if (sizeof($dels)) {
            Db::name('del_chat')->delete($dels);            
        }
    }

    public function clearChatLists()
    {
        $cachekey = 'clearChatLists';
        $lastid = cache($cachekey) ?: 0;
        $delete_user = Db::name('user')->where(['delete_time'=>['>', 0]])->cache(86400)->column('id');
        $delchats = Db::name('chat_lists')->where(['id'=>['>', $lastid]])->field('id,user_id,another_id')->order('id asc')->limit(20000)->select();
        $dels = [];
        foreach ($delchats as $key => $value) {
            if (sizeof($dels) > 15000) break;
            $lastid = $value['id'];
            if (in_array($value['user_id'], $delete_user) || in_array($value['another_id'], $delete_user)) {
                $dels[] = $value['id'];
            }
        }
        cache($cachekey, $lastid, 86400);
        if (sizeof($dels)) {
            Db::name('chat_lists')->delete($dels);            
        }
    }
    public function clearChatLists2()
    {
        $dels = Db::name('chat_lists')->where(['user_time'=>['<', 1672502400], 'another_time'=>['<', 1672502400]])->limit(20000)->column('id');
        if (sizeof($dels)) {
            Db::name('chat_lists')->delete($dels);            
        }
    }
    public function clearChatChargeRecords()
    {
        $cachekey = 'clearChatChargeRecords';
        $lastid = cache($cachekey) ?: 0;
        $delete_user = Db::name('user')->where(['delete_time'=>['>', 0]])->cache(86400)->column('id');
        $delchats = Db::name('chat_charge_records')->where(['id'=>['>', $lastid]])->field('id,user_id,another_id')->order('id asc')->limit(20000)->select();
        $dels = [];
        foreach ($delchats as $key => $value) {
            if (sizeof($dels) > 15000) break;
            $lastid = $value['id'];
            if (in_array($value['user_id'], $delete_user) || in_array($value['another_id'], $delete_user)) {
                $dels[] = $value['id'];
            }
        }
        cache($cachekey, $lastid, 86400);
        if (sizeof($dels)) {
            Db::name('chat_charge_records')->delete($dels);            
        }
    }

    public function chatChargeCheck()
    {
        $user = Db::name('user')->where(['reg'=>1,'delete_time'=>0,'sex'=>'女','last_login_time'=>['>', 0]])->column('id');

        $data = Db::name('chat_charge_records')
            ->alias('c')
            ->join('chat_lists l', 'c.user_id=l.user_id and c.another_id=l.another_id')
            ->where(['c.payer'=>['in', $user], 'c.state'=>1])
            ->field('c.user_id,c.another_id,c.payer,l.user_time,l.another_time')
            ->limit(10000)
            ->select();


        $records = Db::name('chat_charge_check')->where(['state'=>['in', [1,2]]])->column("CONCAT(user_id, '-', another_id)");

        $timenow = time();
        $inserts = [];
        foreach ($data as $value) {
            if (in_array($value['user_id'].'-'.$value['another_id'], $records) || in_array($value['another_id'].'-'.$value['user_id'], $records)) continue;
            if ($value['user_id'] != $value['payer']) {
                $value['another_id'] = $value['user_id'];
                $value['user_id'] = $value['payer'];
            }
            $value['time'] = $value['user_time'] > $value['another_time'] ? $value['user_time'] : $value['another_time'];
            $value['create_time'] = $timenow;
            unset($value['payer'], $value['user_time'], $value['another_time']);
            $inserts[] = $value;
        }

        $ids = Db::name('chat_charge_check')->where(['state'=>0])->column('id');
        if (sizeof($ids)) {
            Db::name('chat_charge_check')->delete($ids);
        }
        Db::name('chat_charge_check')->insertAll($inserts);
    }

    public function lianmaiExceptionCheck()
    {
        $cachekey = 'lianmaiExceptionCheck';
        $lastid = $lastidInit = cache($cachekey) ?: 0;

        $data = Db::name('privatechat')
            ->where(['id'=>['>', $lastid], 'data'=>['like', '%断线%']])
            ->whereTime('addtime', '-2 day')
            ->field('id,data')
            ->select();

        $inserts = [];
        foreach ($data as $key => $value) {
            if (sizeof($inserts) > 15000) break;
            $lastid = $value['id'];

            preg_match_all('/(\d+)断线/', $value['data'], $matches);
            $uids = $matches[1];

            foreach ($uids as $k => $v) {
                if (!isset($inserts[$v])) {
                    $inserts[$v] = ['user_id'=>$v,'exp_count'=>0,'video_count'=>0];
                }
                $inserts[$v]['exp_count']++;
            }
        }
        $timenow = time();
        foreach ($inserts as $key => $value) {
            $inserts[$key]['create_time'] = $timenow;
            $inserts[$key]['video_count'] = Db::name('privatechat')->where(['id'=>['>', $lastidInit], 'type'=>10])->whereTime('addtime', '-2 day')->where(['userid|touserid'=>$key])->count();
        }
        cache($cachekey, $lastid, 600);
        if (sizeof($inserts)) {
            $ids = Db::name('privatechat_lianmai_exception')->column('id');
            if (sizeof($ids)) {
                Db::name('privatechat_lianmai_exception')->delete($ids);
            }
            Db::name('privatechat_lianmai_exception')->insertAll(array_values($inserts));            
        }
    }

    // 当日消费过高，短信提醒
    public function checkspends()
    {
        $start_id = _day_first_id(date('Y-m-d'), 0, 'volley_desc', 'time', 'id');
        $uids = Db::name('volley_desc')->where(['id'=>['>', $start_id], 'types'=>0])->group('user_id')->fetchSql(false)->column("sum(price)", 'user_id');
        // exit($uids);
        var_dump($uids);
        $users = Db::name('user')->where(['id'=>['in', array_keys($uids)]])->column('phone', 'id');
        $max = 1000;

        // $statusStr = array(
        //     "0" => "短信发送成功",
        //     "-1" => "参数不全",
        //     "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
        //     "30" => "密码错误",
        //     "40" => "账号不存在",
        //     "41" => "余额不足",
        //     "42" => "帐户已过期",
        //     "43" => "IP地址限制",
        //     "50" => "内容含有敏感词"
        // );
        $smsapi = "http://api.smsbao.com/";
        $user = getenv('SMSBAO_USER'); //短信平台帐号
        $pass = md5(getenv('SMSBAO_PWD')); //短信平台密码
        $content = "【" . getenv('SMSBAO_SIGN') . "】您今日消费过高，请理性消费";
        foreach ($uids as $key => $value) {
            $cachekey = 'checkspends:'.$key;
            if ($value > $max && isset($users[$key]) && $users[$key]) {
                if (Cache::store('redisUnclear')->get($cachekey)) continue;
                // 发送提醒
                $sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$users[$key]."&c=".urlencode($content);
                $result =file_get_contents($sendurl) ;
                if ($result == 0) {
                    Cache::store('redisUnclear')->set($cachekey, 1, 7200);
                }
            }
        }
    }
    public function MallOrderFanliFun($min = 1)
    {
        if ($min % 5 != 0) return '';
        $day_start = strtotime(date('Y-m-d'));
        $timenow = time();
        if (getenv('APP_MALL_DATABASE') == 'database') {
            $data = Db::name('mall_order_fanli')
                ->where(['state'=>1, 'start_time'=>['between', [1,$day_start]], 'auto_time'=>['<', $day_start]])
                ->limit(1000)
                ->select();
        } else {
            $data = Db::connect(getenv('APP_MALL_DATABASE'))->name('mall_order_fanli')
                ->alias('mof')
                ->join('user_channel_profile ucp', 'mof.user_id=ucp.user_id')
                ->where(['mof.state'=>1, 'mof.start_time'=>['between', [1,$day_start]], 'mof.auto_time'=>['<', $day_start], 'ucp.sys_channel'=>getenv('APP_CHANNEL'), 'ucp.source_type'=>0])
                ->limit(1000)
                ->field('mof.*, ucp.source_uid user_id')
                ->select();
        }
        if (empty($data)) return false;

        $updates = [];
        $fanli_records = [];

        $orders = Db::connect(getenv('APP_MALL_DATABASE'))->name('mall_distribution')
            ->where(['order_id'=>['in', array_column($data, 'order_id')]])
            ->column('user_id,one_uid,two_uid,three_uid', 'order_id');

        if (getenv('APP_MALL_DATABASE') == 'database') {
            $users = Db::name('user')
                        ->where(['id' => ['in', array_column($orders, 'user_id')]])
                        ->column('name,id,sex', 'id');
        } else {
            $users = Db::connect(getenv('APP_MALL_DATABASE'))->name('user')
                        ->alias('u')
                        ->join('user_channel_profile cp', 'u.id=cp.user_id and cp.source_type=0 and sys_channel='.getenv('APP_CHANNEL'), 'left')
                        ->where(['u.id' => ['in', array_column($orders, 'user_id')]])->column('COALESCE(cp.name, u.name) as name,u.id,source_uid', 'u.id');
        }

        Db::startTrans();
        try {

            foreach ($data as $key => $value) {
                if ($value['fanli_count'] <= 0) continue;
                // 今日返利金额
                $today_fanli = $value['fanli_count'] * $value['fanli_day_rate'] / 100;
                // 所剩未返利金额
                $dec_fanli = $value['fanli_count'] - $value['fanlied_count'] - $value['fanlied_dec'];

                $today_long = ($day_start - strtotime(date('Y-m-d', $value['start_time']))) / 86400;

                $state = 1;

                // 今日实际返利金额
                if ($today_fanli > $dec_fanli || $today_long >= $value['fanli_day']) {
                    $today_fanli = $value['fanli_count'] - $value['fanlied_count'];
                    $fanli_dec_sum = 0;
                    $state = 2;
                } else {
                    // 冗余小数
                    $temp_today_fanli = bcdiv(bcmul($today_fanli, '100'), '100', 2);
                    $fanli_dec_offset = $today_fanli - $temp_today_fanli;
                    $fanli_dec_sum = $value['fanlied_dec']+$fanli_dec_offset;
                    $fanli_add = 0;
                    if ($fanli_dec_sum >= 0.01) {
                        $fanli_add = bcdiv(bcmul($fanli_dec_sum, '100'), '100', 2);
                        $fanli_dec_sum -= $fanli_add;
                    }
                    $today_fanli = $temp_today_fanli + $fanli_add;
                }

                $updates[] = [
                    'id'=>$value['id'],
                    'fanlied_rate'=>Db::raw('fanlied_rate+'.$value['fanli_day_rate']),
                    'fanlied_count'=>Db::raw('fanlied_count+'.$today_fanli),
                    'fanlied_dec'=>$fanli_dec_sum,
                    'state'=>$state,
                    'auto_time'=>$timenow
                ];

                $fanli_records[] = [
                    'mall_order_fanli_id'=>$value['id'],
                    'fanli_rate'=>$value['fanli_day_rate'],
                    'fanli_count'=>$today_fanli,
                    'time'=>$timenow
                ];

                $remark = '购买商品-返利计划 id.' . $value['id'];

                // 推广分佣
                if (!$value['goods_id'] && isset($orders[$value['order_id']])) {
                    $level = '3';
                    if ($orders[$value['order_id']]['one_uid']) {
                        $level = '1';
                    } else if ($orders[$value['order_id']]['two_uid']) {
                        $level = '2';
                    }
                    $user = $users[$orders[$value['order_id']]['user_id']] ?? false;
                    if ($user) {
                        $remark = $user['name'] . '('.$user['id'].')' . $remark . ' ' . $level . '级奖励';
                    }
                }

                YaoqingRecords::index($value['user_id'], 0, $today_fanli, $remark, 1, '', 0);
            }
            if (sizeof($updates)) {
                (new MallOrderFanli)->saveAll($updates);
                Db::connect(getenv('APP_MALL_DATABASE'))->name('mall_order_fanli_records')->insertAll($fanli_records);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error($e->getMessage());
        }
    }

    public function ClearYouke()
    {
        // 筛选设备号超长的
        $user_repeat_checks = Db::name('user_repeat_check')->where('CHAR_LENGTH(device_ids)>300')->order('user_id asc')->column('user_id,device_ids,last_login_app_version', 'user_id');
        // 获取所有游客号设备号
        $youke = Db::name('user')->where(['reg'=>0])->column('id','device_id');
        // 获取所有正常用户当前设备号
        $users = Db::name('user')->where(['reg'=>['in', [1,2]]])->where('device_id <> "" and device_id is not null')->column('device_id');
        // 遍历超长设备号是否为游客号
        $rmyk_uids = [];
        $updateRepeats = [];
        $rm_devids = [];
        foreach ($user_repeat_checks as $key => $value) {
            $device_ids = explode(',', $value['device_ids']);
            foreach ($device_ids as $k => $v) {
                if (mb_strlen($v)< 10) continue;
                // 如果是游客号则判断游客号是否还跟其他正常用户当前设备有关联
                if (isset($youke[$v]) && !in_array($v, $users)) {
                    $rmyk_uids[] = $youke[$v];
                    unset($device_ids[$k]);
                    $user_repeat_checks[$key]['device_ids'] = implode(',', $device_ids);
                    $updateRepeats[$key] = ['user_id'=>$key, 'device_ids'=>implode(',', $device_ids)];
                    $rm_devids[] = $v;
                }
            }
        }
        // 没有关联则删除设备号、删除游客号
        if (sizeof($rmyk_uids)) {
            echo "<pre>";
            var_dump($rmyk_uids);
            Db::name('user')->where(['id'=>['in', $rmyk_uids], 'reg'=>0])->delete();
        }
        if (sizeof($updateRepeats)) {
            echo "<br />";
            echo "<br />";
            echo "<br />";
            var_dump($updateRepeats);
            (new UserRepeatCheck)->saveAll(array_values($updateRepeats));
        }
        if (sizeof($rm_devids)) {
            echo "<pre>";
            var_dump($rm_devids);
        }
    }

    public function clearBlackList($min = 0)
    {
        $d = date('d');
        if ($min % 3 != 0 || $d!=1) return false;
        $blacks = Db::name('blacklist')->select();
        $users = Db::name('user')->column('sex', 'id');
        $user_intimate = Db::name('user_intimate')->column('intimate', 'couple_a');

        $last30day = strtotime('-30 day');
        $del = [];
        foreach ($blacks as $value) {
            $sex = $users[$value['user_id']] ?? '';
            if ($sex != '男') continue;
            if (strtotime($value['addtime']) > $last30day) continue;

            $couple_a = $value['user_id'] < $value['to_user'] ? $value['user_id'] . ',' . $value['to_user'] : $value['to_user'] . ',' . $value['user_id'];
            $intimate = $user_intimate[$couple_a] ?? 0;

            if ($intimate) continue;

            $del[] = $value['id'];
            if (sizeof($del) >= 10000) break;
        }

        if (sizeof($del)) {
            Db::name('blacklist')->delete($del);
        }
    }

    public function clearChatViolation($min = 0)
    {
        if (!$min || $min % 9 != 0) return false;
        $chat_violation = Db::name('chat_violation')->where(['is_hidden'=>0])->column('title');
        if (empty($chat_violation)) {
            return false;
        }
        // ini_set('memory_limit', '2048M');

        $chat = Db::name('privatechat')->where(['type'=>['in', [0,12,20,21,22]], 'status'=>['<>', 4]])->whereTime('addtime', '-30 minute')->field('id,content')->select();
        $del = [];
        foreach ($chat as $value) {
            if (sizeof($del)>=5000) break;
            foreach ($chat_violation as $k => $v) {
                if (strpos($value['content'], $v) !== false) {
                    $del[] = $value['id'];
                    break;
                }
            }
        }

        if (empty($del)) {
            return false;
        }

        Db::name('privatechat')->where(['id'=>['in', $del]])->update(['status'=>4]);
    }

    public function mallRebateLoop($min = 0)
    {
        if (!$min || $min % 3 != 0) return false;
        action('api/mall.rebate/loop');
    }

    public function audioToString()
    {
        $data = Db::name('privatechat')
            ->where(['type'=>2])
            ->whereTime('addtime', '-10 minute')
            ->field('id,data,content')
            ->select();

        foreach ($data as $key => $value) {
            $json_data = json_decode($value['data'], true);
            if (isset($json_data['text'])) continue;

            try {
                $result = BaiduApi::Asr('http://'.getenv('APP_URL').$value['content']);
            } catch (\Exception $e) {
                continue;
            }
            if($result){
                $json_data['text'] = $result;

                Db::name('privatechat')->where(['id'=>$value['id']])->update(['data'=>json_encode($json_data, JSON_UNESCAPED_UNICODE)]);
            }
        }
    }

    public function autoImageOcr()
    {
        $cachekey = 'autoImageOcr';
        if (cache($cachekey)) return '';
        cache($cachekey, time(), 600);
        $data = db('auto_image_ocr')->where(['state'=>0])->limit(1)->select();

        // 标注来源
        // 查头像
        // $heads = db('user_material_verify')->where(['types'=>1, 'content'=>['in', array_column($data, 'image')]])->column('content');
        // 查动态
        // 查自定义表情
        // 查消息
        // 查相册
        // 查实名认证
        // 查资料认证
        foreach ($data as $key => $value) {
            // 识别
            $result = \app\service\BaiduApi::imageOCR(getenv('HTTP_TYPE') . '://' . getenv('OSS_DOMAIN') .$value['image']);
            db('auto_image_ocr')->where(['id'=>$value['id']])->update(['state'=>1, 'text'=>json_encode($result, JSON_UNESCAPED_UNICODE)]);
        }
        cache($cachekey, null);
    }


    // 获取未分账的充值订单
    // 为充值订单匹配提现数据
    public function withdraw_match()
    {
        $data = Db::name('order_info')->where(['state'=>0])->order('id asc')->limit(10)->select();

        foreach ($data as $key => $value) {
            $result = \app\service\RechargeWithdrawMatcher::matchWithdrawOrdersFIFO($value['number'], $value['money']);
            if ($result && $result['data'] && sizeof($result['data']['matched_withdraws'])) {
                Db::name('order_info')->where(['id'=>$value['id']])->update(['state'=>1, 'shoper_amount'=>$result['data']['shoper_amount']]);
            }
        }

        $this->payment_confirm_create();
    }

    // 为匹配好提现数据的订单进行分账
    private function payment_confirm_create()
    {
        // 先获取10个不同的recharge_order_no
        $orderNos = Db::name('withdraw_recharge_mapping')
            ->where(['state'=>0])
            ->group('recharge_order_no')
            ->limit(10)
            ->column('recharge_order_no');
        
        // 然后获取这些订单号对应的所有记录
        $results = Db::name('withdraw_recharge_mapping')
            ->where('recharge_order_no', 'in', $orderNos)
            ->order('id asc')
            ->select();
        
        // 按recharge_order_no分组整理结果
        $grouped = [];
        $withdraw_no = [];
        $recharge_order_no = [];
        foreach ($results as $item) {
            $withdraw_no[] = $item['withdraw_no'];
            $recharge_order_no[] = $item['recharge_order_no'];
            $grouped[$item['withdraw_no']][] = $item;
        }

        $order_infos = Db::name('order_info')->where(['number'=>['in', $recharge_order_no]])->column('*', 'number');
        $users = Db::name('withdraw')->where(['order_no'=>['in', $withdraw_no]])->column('userid', 'order_no');
        //halt($grouped);
        foreach ($grouped as $order_no => $list) {
            $div_members = [];
            $orderInfoItem = $order_infos[$item['recharge_order_no']];
            $order_data = json_decode($orderInfoItem['data'], true);
            $payment_id = $order_data['id'];
            // halt($order_data['id']);
            $confirm_amt = 0;
            foreach ($list as $key => $value) {
                if (isset($div_members[$users[$value['withdraw_no']]])) {
                    $div_members[$users[$value['withdraw_no']]]['amount'] += $value['mapping_amount'];
                } else {
                    $div_members[$users[$value['withdraw_no']]] = ['member_id'=>$users[$value['withdraw_no']], 'amount'=>$value['mapping_amount'], 'fee_flag'=>'N'];
                }
                $confirm_amt+=$value['mapping_amount'];
                $div_members[$users[$value['withdraw_no']]]['amount'] = number_format($div_members[$users[$value['withdraw_no']]]['amount'], 2, '.', '');
            }
            $div_members['u0'] = ['member_id'=>0,'amount'=>$orderInfoItem['shoper_amount'], 'fee_flag'=>'Y'];

            Db::startTrans();
            try {
                Db::name('withdraw_recharge_mapping')->where(['id'=>['in', array_column($list, 'id')]])->update(['state'=>1]);;
                $result = action('api/adapay/pay_confirm', [
                    'payment_id'=>$payment_id,
                    'order_no'=>$order_no,
                    'confirm_amt'=>array_sum(array_column(array_values($div_members), 'amount')),
                    //'fee_mode'=> 'O',
                    'div_members'=>array_values($div_members)
                ]);
                $result = $result->getData();
                if ($result['code'] == 200) {
                    Db::commit();
                } else {
                    Db::rollback();
                }
            } catch (\Exception $e) {
                Db::rollback();
            }

        }
        
        // halt($grouped);
    }

    public function timing()
    {
        $d = date('d');
        $hour = date('H');
        $minute = date('i');
        $this->userIncomeYesterday();
        $this->ChargeMallOrderExpire();
        $this->ServiceOrderSettlement();
        $this->updateUserTeam1();
        $this->updateUserTeam2();
        $this->checkActivityOrders();
        $this->minutes();
        $this->tongjiPornoed();

        $this->MallOrderFanliFun($minute);
        $this->clearBlackList($minute);
        $this->clearChatViolation($minute);
        $this->mallRebateLoop($minute);
        $this->autoImageOcr($minute);

        // if ($minute % 5 == 0) $this->checkspends();
        if ($minute == 5) $this->hours();
        if ($hour == 0 && $minute == 0) $this->days();
        if ($hour == 23 && $minute == 55) $this->yesterday();
        if ($minute % 5 == 0) $this->ChatSmsTip();
        if ($minute % 30 == 0) $this->halfAnHour();
        if ($hour == 7 && $minute == 33) $this->mergeWithdraw();
        if ($hour == 18 && $minute == 12) $this->clearwalletrecords();
        if ($minute % 2 == 0) $this->clearBigRecordTables();

        if ($d == 1 && $hour == 2 && $minute == 2) $this->userData3();
        if ($d == 1 && $hour == 2 && $minute == 12) $this->userData2();
        if ($hour == 1 && $minute == 43) $this->userData1();

        if ($minute % 5 == 0) $this->checkUserInviteRecords();
        if ($hour == 0 && $minute == 0) $this->bills();
        if ($hour == 4 && $minute == 33) $this->tongjiAccountant();
        // if ($minute % 15 == 0) $this->insertWishBless();
        if ($hour == 8 && $minute == 33) $this->lianmaiExceptionCheck();
        if ($hour == 8 && $minute == 39) $this->chatChargeCheck();
        if ($minute % 3 == 0) $this->audioToString();
        if ($minute % 4 == 0) $this->checkUnpayTopup();

        //if ($minute % 2 == 1) $this->withdraw_match();
        //$this->withdraw_match();
    }
}
